2014-03-27 127 views
1
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:连接属性尚未初始化。如何解决这个问题?

“的ExecuteReader:Connection属性尚未初始化。”

任何帮助?

+0

是什么Visual Basic中有什么关系呢? – nvoigt

回答

2

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

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

或者你可以通过你的SqlConnectionSqlCommand构造函数作为第二个参数(我总是喜欢)喜欢;

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()) 
     { 
     /// 
     } 
    } 
} 
+1

谢谢,我正在寻找一个小时! – user3467638

+0

@ user3467638你很受欢迎。 –

0

人们很容易忘记这一点。你可以手工设置属性,也可以使之成为习惯后,你连接,构建命令,所以你可以将它传递给构造函数:

SqlConnection cn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Iskola\C#\lotto_kerekeshunor\lotto_kerekeshunor\Database1.mdf;Integrated Security=True;User Instance=True"); 

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

@SonerGönül哎呀,你是对的,谢谢。 – nvoigt

相关问题