我對以下問題感到困惑;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;
}`
感謝您的幫助!
柯
那麼,如果它擊中catch塊,它變得異常,那麼什麼是例外,它是提高? – Arran
供參考。你的代碼中有一個危險的SQL注入機會。您應該強烈考慮閱讀關於SQL注入攻擊以及如何避免它們。 – tgolisch