ExecuteScalar:“;连接未初始化”;

本文关键字:初始化 连接 ExecuteScalar | 更新日期: 2023-09-27 17:59:57

我尝试过这样做,但它实际上不会执行我的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; 

ExecuteScalar:“;连接未初始化”;

您尚未将连接分配给命令:

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属性:

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