【问题标题】:An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll - C# visual studioSystem.Data.dll 中发生“System.InvalidOperationException”类型的未处理异常 - C# Visual Studio
【发布时间】:2017-06-09 17:47:47
【问题描述】:

我有这个代码行,当我尝试将我的数据保存到数据库时显示错误:

System.Data.dll 中出现“System.InvalidOperationException”类型的未处理异常

附加信息:ExecuteNonQuery: A propriedade Connection não foi inicializada。

你们能帮忙吗?

SqlConnection cn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\basededadospap.mdf;Integrated Security=True;Connect Timeout=30");
        SqlCommand cmd = new SqlCommand();

private void button1_Click(object sender, EventArgs e)
        {

            if (textBox4.Text != "" & textBox2.Text != "")
            {
                {
                    using (var connection = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\basededadospap.mdf;Integrated Security=True;Connect Timeout=30"))
                    {
                        cn.Open();
                        cmd.CommandText = "INSERT INTO artigo (nomeartigo,preco) VALUES ('" + textBox4.Text + "','" + textBox2.Text + "')";
                        cmd.ExecuteNonQuery();
                        cmd.Clone();
                        MessageBox.Show(" Artigo inserido com sucesso! ");
                        this.Close();
                    }
                }
            }
        }

【问题讨论】:

  • 能否展示用于创建和初始化 cncmd 的代码?
  • 在这里涂鸦
  • 要么使用cn,要么使用connection,不能同时使用。初始化 cmd : cmd.Connection = cn (或连接)。替代方案:提供到 SqlCommand 构造函数的连接。

标签: c# visual-studio


【解决方案1】:

这是因为你没有告诉你的命令使用连接试试这个:

SqlCommand cmd = new SqlCommand(
    "Query String",
    cn);

您必须告诉您的命令使用哪个连接来查询数据。我看到您的连接名为 cn,因此我们必须将其传递给 SQLCommand 构造函数。

所以你的完整代码看起来像:

using (SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=C:\basededadospap.mdf;Integrated Security=True;Connect Timeout=30"))
{
    con.Open();
    SqlCommand cmd = new SqlCommand("SELECT TOP 3 * FROM Dogs1 ORDER BY Weight", con);
    cmd.ExecuteNonQuery();
    cmd.Clone();
    MessageBox.Show(" Artigo inserido com sucesso! ");
    this.Close();
}

你注意到我是如何将 SQL 命令传递给我的连接变量的吗?

【讨论】:

  • SqlCommand cmd = new SqlCommand("查询字符串",cn); cn 是您发送的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多