我正在使用Visual Studio 2013和SQL Server 2012.我想将数据保存在数据库中,但它提供了:
System.Data.dll中出现未处理的“System.InvalidOperationException”类型异常
我的代码:
private void button1_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand("ups_StudentInsertDetails"))
{
cmd.Parameters.AddWithValue("Name", textBox1.Text);
cmd.Parameters.AddWithValue("Email", textBox2.Text);
//then open connection
conn.Open();
//Execute Reader(select ststement)
//Execute Scalar(select ststement)
//Executenonquery (Insert , update or delete)
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully!");
}
}
}
}
答案 0 :(得分:2)
像这样打开你的sqlconnection并将它与sqlcommand相关联。 请参阅以下注释中突出显示的代码更改。
Private void button1_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
conn.open(); //Open Connection
using (SqlCommand cmd = new SqlCommand("ups_StudentInsertDetails",conn)) //Pass connection to thesqlcommand
{
cmd.Parameters.AddWithValue("Name", textBox1.Text);
cmd.Parameters.AddWithValue("Email", textBox2.Text);
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully!");
}
}
}
}
答案 1 :(得分:1)
SqlCommand
不包含您要开放的SqlConnection
。首先。您可以使代码更容易删除,并在执行命令之前打开连接:
private void button1_Click(object sender, EventArgs e)
{
string connString = ConfigurationManager.ConnectionStrings["dbx"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("ups_StudentInsertDetails", conn);
cmd.Parameters.AddWithValue("Name", textBox1.Text);
cmd.Parameters.AddWithValue("Email", textBox2.Text);
//then open connection
cmd.Connection.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Data saved successfully!");
}
}