【问题标题】:Connection string property has not been initialized SqlCommandBuilder连接字符串属性尚未初始化 SqlCommandBuilder
【发布时间】:2017-09-14 04:32:50
【问题描述】:

我尝试从 Windows 窗体应用程序更新我的数据库。信息显示在 datagridview 中。当我单击更新按钮时,出现异常:

连接字符串属性尚未初始化

cmdBuilder.DataAdapter.UpdateCommand = null

我的代码:

public static string connectionString = @"Data Source=(local)\SQLEXPRESS;Initial Catalog=Clothing_DB;Integrated Security=True;Connect Timeout=15;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False";
public void setNewSizes()
{
    using (SqlConnection conn = new SqlConnection(connectionString))
    {
            try
            {
                conn.Open();
                adapterSize.UpdateCommand = cmdBuilder.GetUpdateCommand(); //error here
                adapterSize.Update(recivedData.Tables[0]);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, ex.Source);
            }
    }
}

我可以修复它吗?

【问题讨论】:

  • 从您的源代码中不清楚您是否传递了对 Command 对象的 Connection 属性的连接引用
  • 你为什么要创建一个连接对象却从不使用它?
  • @john 用于:尝试 { conn.Open();
  • 好的。我会改写。为什么要创建连接对象并打开与数据库的连接只是为了不使用它然后将其丢弃?这似乎毫无意义和浪费。
  • @john 你是什么意思?

标签: c# sql-server database winforms datagridview


【解决方案1】:

connectionString 属性使用“查找所有引用”来查找它的初始化。 检查您的项目,连接字符串值通常存储在 App.config 或项目属性中。或硬编码。

【讨论】:

    【解决方案2】:

    您不应释放在创建SqlDataAdapter 期间创建的SqlConnection 对象。您不应该使用新连接,也无需打开和关闭它,SqlDataAdapter.Update(yourTable) 会为您完成。

    【讨论】:

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