Domanda

I attempted this but it won't actually perform my ExecuteScalar statement - it throws an error: "ExecuteScalar connection has not been initialized".

bool valid = false;
SqlConnection sqlconn = new SqlConnection(cstr);
SqlCommand sqlcomm = new SqlCommand("Select case when exists ((Select id, phone, address From sys.views where name = 'employeedatabase')) Then 1 else 0 end");
sqlconn.Open();
//Here is where the error hits
valid = (int)sqlcomm.ExecuteScalar() == 1; 
È stato utile?

Soluzione

You haven't assigned the connection to the command:

SqlCommand sqlcomm = new SqlCommand("Select case when exists ((Select id, phone, address From sys.views where name = 'employeedatabase')) Then 1 else 0 end", sqlconn);

You can either use the constructor overload as shown above or the Connection property:

SqlCommand sqlcomm = new SqlCommand("Select case when exists ((Select id, phone, address From sys.views where name = 'employeedatabase')) Then 1 else 0 end");
sqlcomm.Connection = sqlconn;

Side-note: i would use the using-statement to ensure that the connection gets closed even on error:

using(SqlConnection sqlconn = new SqlConnection(cstr))
using(SqlCommand sqlcomm = new SqlCommand("Select case when exists ((Select id, phone, address From sys.views where name = 'employeedatabase')) Then 1 else 0 end", sqlconn))
{
    sqlconn.Open();
    // ...
} // you don't need to close it yourself
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top