6

为了运行executeScalar,我在 Internet 上尝试了很多建议,但我得到了错误ExecuteScalar: Connection property has not been initialized。我的INSERT查询工作正常,问题出在executeScalar.

conn.Open();
SqlCommand cmd = new SqlCommand(
    "INSERT INTO Products (Product_Name,Product_BarCode,Product_CP,Product_SP,
                           Product_Countainer,Product_Pcs,Product_MFGDate,
                           Product_ExpiryDate,Product_Grade)
     Values ('" + Name.Text + "','" + BarCode.Text + "','" + CostP.Value + "','" + 
             SellingP.Value + "','" + Countainer.Value + "','" + Pcs.Value + "','" + 
             MfgDate.Value + "','" + ExpDate.Value + "','" + Grade.SelectedItem + "')", 
     conn);
cmd.ExecuteNonQuery();
conn.Close();
conn.Open();
cmd.Connection = conn;
cmd = new SqlCommand("SELECT SUM(Product_CP) FROM Products AS Amount");
Amount = (double)cmd.ExecuteScalar();
MessageBox.Show(Amount.ToString());
conn.Close();
4

3 回答 3

15
cmd = new SqlCommand(...);

正如错误明确指出的那样,此命令没有连接。

于 2012-12-04T19:16:42.077 回答
0

如果您使用 DBCommand 而不是 SQLCommand,这将无法解决问题,因为 DBCommand 是一个抽象类并且无法实例化..

对我有用的解决方案是:我在必须使用的地方使用 command.executeScalar():DbCommand.executeScalar (command) // 效果很好!

于 2015-07-17T09:41:58.237 回答
0

cmd.Connection = conn;

应该在声明之后

cmd = new SqlCommand("SELECT SUM(Product_CP) FROM Products AS Amount");
cmd.Connection = conn;
于 2022-02-02T21:24:56.027 回答