C# 使用SQL DataReader中的变量

C# 使用SQL DataReader中的变量,c#,sql,winforms,C#,Sql,Winforms,我已经用DataReader阅读了int“anzahl”。现在我想用这个号码。问题是:我无法从while循环外部访问int。错误显示“使用未分配的局部变量”。如何提供“anzahl”?这是我的密码: int anzahl; string uid = uidTextbox.Text; string query1 = string.Format("SELECT Chip_Anzahl FROM chipTable WHERE Chip_ID = '{0}';",

我已经用DataReader阅读了int“anzahl”。现在我想用这个号码。问题是:我无法从while循环外部访问int。错误显示“使用未分配的局部变量”。如何提供“anzahl”?这是我的密码:

int anzahl;
string uid = uidTextbox.Text;
string query1 = string.Format("SELECT Chip_Anzahl FROM chipTable WHERE Chip_ID = '{0}';",
                              uid);

try
{
    sqlConnection = new SqlConnection(connectionString);
    SqlCommand sqlCmd = new SqlCommand(query1, sqlConnection);
    sqlCmd.CommandText = query1;

    sqlConnection.Open();
    SqlDataReader dataReader = sqlCmd.ExecuteReader();

    while(dataReader.Read())
    {
        anzahl = dataReader.GetInt32(0);
    }

    dataReader.Close();
    sqlConnection.Close();
}
catch (Exception E)
{
    MessageBox.Show(E.ToString());
}

int newnumb = anzahl + 5;
MessageBox.Show(newnumb.toString());

您遇到的具体问题是,C#无法确定anzahl是否为。也就是说,在某些情况下,该线路从未运行:

anzahl = dataReader.GetInt32(0);
但这一行仍然有:

int newnumb = anzahl + 5;
如果发生这种情况,
anzahl
未定义,这是不允许的

朴素的修正是对变量声明的简单调整:

int anzahl = 0;
这将允许代码按预期编译和运行(大部分)。然而,可能值得你花时间去了解这些边缘案例。。。特别是注释中描述的SQL注入的边缘情况

更完整的修复可能如下所示:

//put this in a separate file, and move ALL database access into this class
public static class DB
{
    private string ConnectionString {get;} = "connection string here";
   
    public static int GetAnzahlByChipUID(string chipUID)
    {
        string query1 = "SELECT Chip_Anzahl FROM chipTable WHERE Chip_ID = @chipUID;",
                            
        using (var sqlConnection = new SqlConnection(ConnectionString))
        using (var sqlCmd = new SqlCommand(query1, sqlConnection))
        {
            sqlCmd.Parameters.Add("@chipUID", SqlDbtype.VarChar, 64).Value = chipUID;

            sqlConnection.Open();
            return (int)sqlCmd.ExecuteScalar();
        }
    }
}

//Then call it from the existing location like this:
try 
{
    int anzahl = DB.GetAnzahlByChipUID(uidTextbox.Text);
    int newnumb = anzahl + 5;
    MessageBox.Show(newnumb.ToString());
}
catch (Exception E)
{
    MessageBox.Show(E.Message);
}

注意使用
sqlCmd.Parameters
设置
@chipUID
的值。这不会进行简单的字符串替换。Real injection protection将参数数据隔离在与SQL命令文本完全不同的区域中,以防止任何注入的可能性。

-您不应该将SQL语句连接在一起-使用参数化查询来避免SQL注入-签出|
int anzahl=0这是否回答了您的问题?而且,似乎这应该是一种
ExecuteScalar()
情况,而不是
ExecuteReader()