Skip to main content
 首页 » 编程设计

c#之执行标量 : "Connection not initialized"

2024年02月13日12zhenyulu

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

请您参考如下方法:

您还没有为命令分配连接:

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-statement 来确保即使出现错误也能关闭连接:

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