Question

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]++;
    }
}

I have this code, I want to read datas from database then compare them. Visual Basic says

"ExecuteReader: Connection property has not been initialized."

Any help?

Was it helpful?

Solution

Looks like you didn't initialize your SqlCommand.Connection property. Without this, your program can't know to execute your SqlCommand using which SqlConnection. Just add;

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

Or you can pass your SqlConnection to your SqlCommand constructor as a second parameter (which I always prefer) like;

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

Also use using statement to dispose your SqlConnection, SqlCommand and SqlDataReader like;

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

OTHER TIPS

It's easy to forget this. You can set the property by hand, or you can make it a habit to construct commands after your connection, so you can pass it to the constructor:

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top