我有这些代码行,当我尝试将数据保存到数据库时显示错误:
System.Data.dll中出现未处理的“System.InvalidOperationException”类型异常
其他信息:ExecuteNonQuery:一个支持连接nãofoiinicializada。
你能给我们一些帮助吗?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();
}
}
}
}
答案 0 :(得分:0)
因为你没有告诉你的命令使用连接试试这个:
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命令传递连接变量?