c# - ExecuteReader : Connection property has not been initialized. 如何解决这个问题?

标签 c# sql database connection

int tempid,temp1,temp2,temp3,temp4,temp5,temp6;
{
    SqlCommand cmd = new SqlCommand("select * from Szelvenyek");
    SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Iskola\C#\lotto_kerekeshunor\lotto_kerekeshunor\Database1.mdf;Integrated Security=True;User Instance=True");
    cn.Open();
    SqlDataReader dr = cmd.ExecuteReader();
    while (dr.Read())
    {
        tempid = (int)dr["ID"];
        temp1 = (int)dr["elso"];
        temp2 = (int)dr["masodik"];
        temp3 = (int)dr["harmadik"];
        temp4 = (int)dr["negyedik"];
        temp5 = (int)dr["otodik"];
        temp6 = (int)dr["hatodik"];

        if (r1 == temp1 || r1 == temp2 || r1 == temp3 || r1 == temp4 || r1 == temp5 || r1 == temp6) talalat[tempid]++;
        if (r2 == temp1 || r2 == temp2 || r2 == temp3 || r2 == temp4 || r2 == temp5 || r2 == temp6) talalat[tempid]++;
        if (r3 == temp1 || r3 == temp2 || r3 == temp3 || r3 == temp4 || r3 == temp5 || r3 == temp6) talalat[tempid]++;
        if (r4 == temp1 || r4 == temp2 || r4 == temp3 || r4 == temp4 || r4 == temp5 || r4 == temp6) talalat[tempid]++;
        if (r5 == temp1 || r5 == temp2 || r5 == temp3 || r5 == temp4 || r5 == temp5 || r5 == temp6) talalat[tempid]++;
        if (r6 == temp1 || r6 == temp2 || r6 == temp3 || r6 == temp4 || r6 == temp5 || r6 == temp6) talalat[tempid]++;
    }
}

我有这段代码,我想从数据库中读取数据然后比较它们。 Visual Basic 说

"ExecuteReader: Connection property has not been initialized."

有什么帮助吗?

最佳答案

看起来你没有初始化你的 SqlCommand.Connection属性(property)。没有这个,您的程序就无法知道使用哪个 SqlConnection 来执行您的 SqlCommand。只需添加;

cmd.Connection = cn;
cn.Open();
...

或者您可以将 SqlConnection 作为第二个参数(我一直喜欢)传递给您的 SqlCommand

SqlCommand cmd = new SqlCommand("select * from Szelvenyek", cn);

也可以使用 using statement处理你的 SqlConnectionSqlCommandSqlDataReader

using(SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Iskola\C#\lotto_kerekeshunor\lotto_kerekeshunor\Database1.mdf;Integrated Security=True;User Instance=True"))
using(SqlCommand cmd = new SqlCommand("select * from Szelvenyek", cn))
{
   cn.Open();
   using(SqlDataReader dr = cmd.ExecuteReader())
   {
      while(dr.Read())
      {
         ///
      }
   }
}

关于c# - ExecuteReader : Connection property has not been initialized. 如何解决这个问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22681785/

相关文章:

c# - WPF CommandParameter MultiBinding 值为 null

c# - OleDb 异常

mysql - 选择所有 child 都满足条件的 self 关系中的行

sql - ADODB/Excel 查询错误

php - Laravel null 对象 hasMany 关系

mysql - 如何为数据库生成 ERD 或 UML?

c# - pictureBox 图像处理异常

c# - 将带有 CheckedChanged 事件的复选框添加到动态 GridView

sql - 对于增值税,SQL Server 字段大小声明的正确 Decimal(p, s) 精度和小数位数是多少?

mysql - 选择和更新 MySQL 查询