ExecuteScalar:尚未初始化Connection属性

时间:2012-12-04 19:13:15

标签: sql-server-2008 c#-4.0

为了运行executeScalar,我在互联网上尝试了很多建议,但收到错误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 Ammount");
Ammount = (double)cmd.ExecuteScalar();
MessageBox.Show(Ammount.ToString());
conn.Close();

2 个答案:

答案 0 :(得分:12)

cmd = new SqlCommand(...);

由于错误明确指出,此命令没有连接。

答案 1 :(得分:0)

如果你使用的是DBCommand而不是SQLCommand,那么由于DBCommand是一个抽象类而无法实例化,因此无法解决问题。

对我有用的解决方案是:我使用的是command.executeScalar(),我必须使用:DbCommand.executeScalar(command)//可以创造奇迹!