gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 21:33:02 25 4
gpt4 key购买 nike

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

关于c# - 执行标量 : "Connection not initialized",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23270081/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com