【问题标题】:Working with variable from SQL DataReader [duplicate]使用 SQL DataReader 中的变量 [重复]
【发布时间】:2021-08-25 20:13:30
【问题描述】:

我已经用 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# sql winforms


【解决方案1】:

您遇到的具体问题是 C# 无法确定 anzahldefinitely assigned。也就是说,在某些情况下,这条线永远不会运行:

anzahl = dataReader.GetInt32(0);

但这行仍然有效:

int newnumb = anzahl + 5;

如果发生这种情况,anzahl 是未定义的,这是不允许的。

天真的修复是对变量声明的简单调整:

int anzahl = 0;

这将允许代码按您的预期编译和运行(大部分)。但是,可能值得您花时间进一步了解这些边缘情况...尤其是关于 SQL INJECTION 的边缘情况,如 cmets 中所述。

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

//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 的值。这不会进行简单的字符串替换。真正的注入保护将参数数据与 SQL 命令文本隔离在一个完全独立的区域中,以防止任何注入的可能性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-09-22
    • 1970-01-01
    • 2015-11-16
    • 2021-10-27
    • 1970-01-01
    相关资源
    最近更新 更多