ExecuteScalar:"连接未初始化"

时间:2014-04-24 13:16:50

标签: c# ado.net

我尝试了这个,但它实际上没有执行我的ExecuteScalar语句 - 它会抛出一个错误:" ExecuteScalar连接尚未初始化"。

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; 

1 个答案:

答案 0 :(得分:4)

您尚未分配与命令的连接:

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

您可以使用如上所示的构造函数重载或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;

旁注:我会使用using - 语句来确保连接即使在出错时也会关闭:

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
相关问题