【问题标题】:ExecuteScalar: Connection property has not been initializedExecuteScalar:连接属性尚未初始化
【发布时间】:2012-12-04 19:13:15
【问题描述】:

为了运行 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();

【问题讨论】:

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


【解决方案1】:
cmd = new SqlCommand(...);

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

【讨论】:

  • +1 我错误地认为将事务分配给命令就足够了,因为事务具有连接。但是不,我需要将命令的连接设置为命令事务的连接属性。
  • @KirkKuykendall ,我可以理解在using 之外时的这种行为,但是在using 块内时,应该使用什么连接似乎很明显。但我想我可以说清楚。
  • 我真的不明白该怎么做。你能详细说明如何处理cmd = new SqlCommand(...)吗?
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    这个cmd.Connection = conn;

    应该在声明之后

    cmd = new SqlCommand("SELECT SUM(Product_CP) FROM Products AS Amount");
    cmd.Connection = conn;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-03
      • 2011-07-22
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多