【问题标题】:ExecuteScalar has not been initialized [duplicate]ExecuteScalar 尚未初始化 [重复]
【发布时间】:2015-12-16 11:07:16
【问题描述】:

我不断收到此错误消息,说"ExecuteScalar has not been initialized" 我是 C# 新手,但通过 google 和教程查看了一下,仍然看不到问题所在。这可能是一个非常愚蠢的错误,但如果有人可以提供帮助。谢谢:)

           // open connection 
           myConnection.Open();


           // sql command 
           string Account_Num = txt_acc.Text;
           string Pin_num = txt_pin.Text;


           SqlCommand check_details = new SqlCommand("select Account_num, Pin_num from Cust_details where Account_num='" + txt_acc.Text + "'and Pin_num ='" + txt_pin.Text + "'"); 
           check_details.Parameters.AddWithValue("@Account_num", txt_acc.Text);
           check_details.Parameters.AddWithValue("@Pin_num", txt_pin.Text);


           int result = Convert.ToInt32(check_details.ExecuteScalar());

           if (result > 0)
           {
               Console.WriteLine("user exists");
           }


           else
           {
               Console.WriteLine("error");
           }
       }

【问题讨论】:

  • 如果您在网上搜索过实际异常,您可能会找到duplicate。 :)
  • 您需要为您的命令提供连接名称。还有为什么在参数中添加 acco_num 和 pin_num 时要在查询中添加它们?

标签: c#


【解决方案1】:

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

check_details.Connection = myConnection;

或者你可以在你的SqlCommand构造函数中设置它作为第二个参数;

SqlCommand check_details = new SqlCommand("yourCommand", myConnection);

或者您可以使用连接中的CreateCommand method

SqlCommand check_details = myConnection.CreateCommand();

你误解了parameterized queries。您仍然在您的 sql 查询中进行字符串连接,但您尝试添加参数。这是没有意义的。

使用using statement 也可以自动处理您的连接和命令。

也不要尽可能多地使用AddWithValueIt may generate unexpected and surprising results sometimes。使用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 会忽略它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多