C# ExecuteScalar尚未初始化

C# ExecuteScalar尚未初始化,c#,C#,我一直收到这样一个错误,说“ExecuteScalar尚未初始化”我刚接触C,但浏览了谷歌和教程,仍然看不出问题出在哪里。这可能是一个非常愚蠢的错误,但如果有人能帮忙的话。谢谢:) 看起来您没有将命令与连接连接起来。只需将其设置为myConnection check_details.Connection = myConnection; 或者您可以在SqlCommand构造函数中将其设置为第二个参数 SqlCommand check_details = new SqlCommand("yourC

我一直收到这样一个错误,说
“ExecuteScalar尚未初始化”
我刚接触C,但浏览了谷歌和教程,仍然看不出问题出在哪里。这可能是一个非常愚蠢的错误,但如果有人能帮忙的话。谢谢:)


看起来您没有将命令与连接连接起来。只需将其设置为
myConnection

check_details.Connection = myConnection;
或者您可以在
SqlCommand
构造函数中将其设置为第二个参数

SqlCommand check_details = new SqlCommand("yourCommand", myConnection);
或者,您可以使用您的连接

SqlCommand check_details = myConnection.CreateCommand();
你被误解了。您仍然在sql查询中进行字符串连接,但尝试添加参数。那没有意义

用于自动处理连接和命令

也不要尽可能多地使用
AddWithValue
。使用
Add
方法重载指定参数类型及其大小

using(var myConnection = new SqlConnection(conString))
using(var check_details = myConnection.CreateCommand())
{
    check_details.CommandText = @"select Account_num, Pin_num from Cust_details 
                                  where Account_num = @accnum
                                  and Pin_num = @pinnum";
    // I assume your column types as Int
    check_details.Parameters.Add("@accnum", SqlDbType.Int).Value = int.Parse(txt_acc.Tex);
    check_details.Parameters.Add("@pinnum", SqlDbType.Int).Value = int.Parse(txt_pin.Text);
    myConnection.Open();
    int result = (int)check_details.ExecuteScalar();
    ...
}

顺便说一下,在命令中选择
Pin_num
列是没有意义的,因为
ExecuteScalar
会忽略它。

如果您在web上搜索实际的异常,您可能已经找到了。:)您需要为您的命令指定连接名称。另外,当您在参数中添加acco_num和pin_num时,为什么要在查询中添加acco_num和pin_num?
using(var myConnection = new SqlConnection(conString))
using(var check_details = myConnection.CreateCommand())
{
    check_details.CommandText = @"select Account_num, Pin_num from Cust_details 
                                  where Account_num = @accnum
                                  and Pin_num = @pinnum";
    // I assume your column types as Int
    check_details.Parameters.Add("@accnum", SqlDbType.Int).Value = int.Parse(txt_acc.Tex);
    check_details.Parameters.Add("@pinnum", SqlDbType.Int).Value = int.Parse(txt_pin.Text);
    myConnection.Open();
    int result = (int)check_details.ExecuteScalar();
    ...
}