2012-12-03 56 views
1

我對以下問題感到困惑;C#SqlDataReader for int

我想使用SqlDataReader檢索記錄(列'EmployeeId'(int))。

當我直接在服務器上運行查詢時,我得到了正確的記錄。當我運行相同的過程來獲得另一列(字符串)我正確地得到了記錄。

我假設問題是由於這樣的事實,我試圖讓一個int,程序跳過

while (mySqlDbDataReader.Read()) 

,並直接進入

catch (Exception eMsg1) 
      { 

下面是完整的程序

public string getUserId() 
{ 
    //Check user details against login in Db 
    //Local variables to capture values from Db 
    string varId = ""; 

    //Connection string 
    conn = sqlDbConnection.GetConnection(); 
    SqlCommand newCmd = conn.CreateCommand(); 
    newCmd.Connection = conn; 
    newCmd.CommandType = CommandType.Text; 

    //Query 
    userCredentials connectedUser = new userCredentials(); 
    newCmd.CommandText = "SELECT EmployeeId FROM tblEmployees WHERE WinLogin='" + connectedUser.getWindowsLogin() + "';"; 

    //Connect 
    newCmd.Connection = conn; 
    conn.Open(); 

    //Utilisation du try-catch permettant de fermer la connexion même en cas de plantage 
    try 
    { 
     SqlDataReader mySqlDbDataReader = newCmd.ExecuteReader(); 
     while (mySqlDbDataReader.Read()) 
     { 
      //Tester que le résultat n’est pas NULL afin d’éviter un plantage au moment du crash 
      if (mySqlDbDataReader["EmployeeId"] != System.DBNull.Value) 
      { 
       //Récupérer le nom à l’aide d’un cast 
       varId = (string)mySqlDbDataReader["EmployeeId"];       
      } 
      else 
      { 
       varId = "Unknown";      
      } 
     } 
    } 
    catch (Exception eMsg1) 
    { 
     //In the event of trouble, display error msg 
     //MessageBox.Show("Error while executing query: " + eMsg1.Message); 
     Console.WriteLine(eMsg1); 

     //Control 
     MessageBox.Show("Empty"); 
    } 
    finally 
    { 
     //Close DB connection 
     conn.Close(); 
    } 

    return varId; 
}` 

感謝您的幫助!

+1

那麼,如果它擊中catch塊,它變得異常,那麼什麼是例外,它是提高? – Arran

+1

供參考。你的代碼中有一個危險的SQL注入機會。您應該強烈考慮閱讀關於SQL注入攻擊以及如何避免它們。 – tgolisch

回答

7

我想使用SqlDataReader檢索記錄(列'EmployeeId'(int))。

那麼,爲什麼你要鑄造一個字符串?

varId = (string)mySqlDbDataReader["EmployeeId"]; 

這就是問題所在。你應該它轉換成一int,而不是,或使用GetInt32

// You don't need a local variable for this at all... 
return mySqlDbDataReader.GetInt32(0); 

(這裏0是「EmployeeId列的順序,你可以用GetOrdinal拿到依次爲一個名爲列。)

你需要你的方法的返回類型更改爲int爲好,當然 - (我強烈反對這樣做雖然)或撥打ToString如果你真的值作爲一個字符串

當您將異常寫入控制檯時,您應該能夠看到詳細信息。我不認爲執行跳過Read調用 - 它正在讀取結果,然後未能將int轉換爲string,導致引發異常。

+0

謝謝大家的快速回復;) – Brice

+0

您不能在'GetInt32(...)'方法中傳遞列名。它只接受'從零開始的列序號'。 – shashwat

+0

@AnimalsAreNotOursToEat:是的,我總是忘記這一點。將編輯。 –

0

嘗試轉換的INT:中

代替

//Récupérer le nom à l’aide d’un cast 
varId = (string)mySqlDbDataReader["EmployeeId"]; 

使用

//Récupérer le nom à l’aide d’un cast 
varId = mySqlDbDataReader["EmployeeId"].ToString(); 

當然這是假設EmployeeId不能爲空的。

+0

兩者有什麼區別? – dotNET

+0

哈!複製並貼上了我! –

1

您正在將int轉換成string,這是您無法做到的。

// Change varId to an int and cast to an int 
varId = (int)mySqlDbDataReader["EmployeeId"]; 

或者

// Call ToString to get the string representation of the underlying value 
varId = mySqlDbDataReader["EmployeeId"].ToString(); 
1

兩個容斯是正確的。這只是演員似乎在提出問題。我想建議您使用Typed QueryTableAdapter來達到您的目的。只需將新的DataSet添加到您的項目中,右鍵單擊DataSet設計器並添加一個查詢。在那裏鍵入你的查詢,引入你的變量(在這種情況下我猜用戶名),它會在你的QueryAdapter中生成一個查詢函數,它將接受你的變量,運行查詢並返回EmployeeID。此外,它還可以幫助您從SQL注入類型的東西中解脫出來,因​​爲它在內部使用了輸入參數。