C#SqlDataReader for int

Bri*_*ice 1 c# int integer sqldatareader

我对以下问题感到困惑;

我正在尝试使用SqlDataReader检索记录(列'EmployeeId'(int)).

当我直接在服务器上运行查询时,我正确地获得了记录.当我运行相同的过程来获取另一列(字符串)时,我正确地获得了记录.

我认为问题是由于我试图获得一个int,程序跳过了

while (mySqlDbDataReader.Read())
Run Code Online (Sandbox Code Playgroud)

并直接去

catch (Exception eMsg1)
            {
Run Code Online (Sandbox Code Playgroud)

这是完整的程序

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;
}`
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

布莱斯

Jon*_*eet 7

我正在尝试使用SqlDataReader检索记录(列'EmployeeId'(int)).

那么你为什么要投射到一个字符串?

varId = (string)mySqlDbDataReader["EmployeeId"];
Run Code Online (Sandbox Code Playgroud)

那就是问题所在.您应该将其转换为int替代,或使用GetInt32:

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

(这里0是" EmployeeId列的序数;您可以GetOrdinal用来获取命名列的序数.)

当然,您还需要更改方法的返回类型int- 或者ToString如果您真的希望将值作为字符串调用.(我强烈建议不要这样做.)

将异常写入控制台时,您应该能够看到详细信息.我不认为执行正在跳过Read调用 - 它正在读取结果,然后无法将其转换int为a string,从而导致抛出异常.