2012-04-13 61 views
4

這裏的時候是我GeneralFunctions:「無效的嘗試時,不存在數據讀取」使用SqlDataReader的

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Configuration; 
using System.Data; 
using System.Data.SqlClient; 

/// <summary> 
/// Summary description for GeneralFunctions 
/// </summary> 
public class GeneralFunctions 
{ 
    public GeneralFunctions() 
    { 
     // 
     // TODO: Add constructor logic here 
     // 
    } 

    public static DataTable GetData (string query) 
    { 
     SqlDataAdapter dataAdapter; 
     DataTable table; 

     try 
     { 
      dataAdapter = new SqlDataAdapter(query, GetConnectionString()); 
      table = new DataTable(); 

      dataAdapter.Fill(table); 
      return table; 
     } 
     catch (Exception ex) 
     { 
     } 
     finally 
     { 
      dataAdapter = null; 
      table = null; 
     } 

     return table; 
    } 

    private static string GetConnectionString() 
    { 
     string connectionString = ConfigurationManager.ConnectionStrings[ "CAPortalConnectionString" ].ConnectionString; 

     return connectionString; 
    } 

    public static int? AuthenticateLogin (string username, string password) 
    { 
     using (var conn = new SqlConnection(GetConnectionString())) 
     using (var cmd = conn.CreateCommand()) 
     { 
      conn.Open(); 
      cmd.CommandText = 
      @"SELECT 
       DistID 
      FROM 
       Distributor 
      WHERE 
       Username = @username 
      AND 
       Password = @password"; 
      cmd.Parameters.AddWithValue("@username", username); 
      cmd.Parameters.AddWithValue("@password", password); 
      using (var reader = cmd.ExecuteReader()) 
      { 
       if (!reader.Read()) 
       { 
        // no results found 
        return null; 
       } 
       return reader.GetInt32(reader.GetOrdinal("DistID")); 
      } 
     } 
    } 

    public static string GetDistInfo (int distID) 
    { 
     using (var conn = new SqlConnection(GetConnectionString())) 
     using (var cmd = conn.CreateCommand()) 
     { 
      conn.Open(); 
      cmd.CommandText = 
      @"SELECT 
       FName + ' ' + LName AS Name 
      FROM 
       Distributor 
      WHERE 
       DistID = @distid"; 
      cmd.Parameters.AddWithValue("@distid", distID); 
      using (var reader = cmd.ExecuteReader()) 
      { 
       return reader.GetString(reader.GetOrdinal("Name")); 
      } 
     } 
    } 

} 

這是我的登錄頁面:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

public partial class index : System.Web.UI.Page 
{ 
    protected void Page_Load (object sender, EventArgs e) 
    { 

    } 
    protected void but_login_Click (object sender, EventArgs e) 
    { 
     if (username_id.Text != "" || password.Text != "") 
     { 
      // Verify the username and password match the database 
      var distId = GeneralFunctions.AuthenticateLogin(username_id.Text, password.Text); 

      if (distId != null) 
      { 
       // User is authenticated 
       var name = GeneralFunctions.GetDistInfo((int)distId); 
       Session[ "DistName" ] = name; 
       Session[ "DistID" ] = distId; 

       Response.Redirect("dashboard.aspx", false); 
      } 
      else 
      { 
       // provide error label here username and password do not match 
       authentFailed.Text = "Username/Password did not match our records"; 
      } 
     } 
     else 
     { 
      // Username or Password blank error lable 
      authentFailed.Text = "Please Input Username/Password"; 
     } 
    } 
} 

之前我加入了GetDistInfo方法,它的工作很好,登錄用戶。然後我嘗試添加會話變量和GetDistInfo方法。我將從AuthenticateLogin返回的DistID傳入GetDistInfo方法。它出錯並出現以下錯誤:

異常詳細信息:System.InvalidOperationException:無數據存在時嘗試讀取無效。

Source Error: 

Line 95:    using (var reader = cmd.ExecuteReader()) 
Line 96:    { 
Line 97:     return reader.GetString(reader.GetOrdinal("Name")); 
Line 98:    } 
Line 99:   } 


Source File: c:\inetpub\wwwroot\Base\ClientAccessPortal\App_Code\GeneralFunctions.cs Line: 97 

當我對數據庫運行SQL時,它正確地取回客戶端名稱。我不確定爲什麼它沒有在代碼中這麼做。任何人都能看到我缺少的東西?

回答

10

請嘗試替換此。其實Read()在您的代碼中缺失。

using (var reader = cmd.ExecuteReader()) 
{ 
    // you haven't positioned yourself on a record yet. 
    while (reader.Read()) 
    { 
     return reader.GetString(reader.GetOrdinal("Name")); 
    } 
    return string.Empty; 
} 

編輯 回答:

using (var reader = cmd.ExecuteReader()) 
{ 
    return reader.GetString(reader.GetOrdinal("Name")); 
} 

用以下

using (var reader = cmd.ExecuteReader()) 
{ 
    if(reader.Read()) 
    { 
      return reader.GetString(reader.GetOrdinal("Name")); 
    } 
    return null; 
} 
+0

我添加了返回null,並修復了它。你能幫我理解爲什麼當讀取總是返回一個結果時,這是爲了尋找一個null? – 2012-04-13 18:50:37

+0

編譯器注意到沒有返回語句。編譯器無法證明代碼路徑永遠不會離開,所以它期望碰到返回語句。 – Pankaj 2012-04-13 18:57:05

+0

你是第一個發佈返回null解決方案,它的工作就像一個魅力。必須檢查這個答案。謝謝大家的幫助和快速回復。 – 2012-04-13 19:10:17

2

請先閱讀(你在代碼中使用時,在識別器這樣做)到你得到的錯誤;自定義您的功能

public static string GetDistInfo (int distID) 

所有可能的方式「走出函數」必須返回的東西。在你的情況下,你應該返回一個字符串或可能爲null,取決於你想要做什麼。

+0

這似乎是朝着正確的方向邁出的一步,但它現在給我一個新的錯誤:編譯器錯誤信息:CS0161:'GeneralFunctions.GetDistInfo(int)':並非所有代碼路徑都返回一個值'Anyideas? – 2012-04-13 18:43:10

+0

請檢查我的編輯。 – Pankaj 2012-04-13 18:45:30

+0

'String.Empty'將會像巧克力一樣記憶。 – Pankaj 2012-04-13 18:54:44

相關問題