1. 1.ExecuteNonQuery:连接属性尚未初始化“.2.这是我执行以下代码时出现的错误。
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection();
conn.ConnectionString = @"Data Source=Sadiq;Initial Catalog=rafi;Integrated Security=True";
conn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "student";
int studid = Convert.ToInt32(TextBox1.Text);
string name = TextBox2.Text;
int age = Convert.ToInt32(TextBox3.Text);
string school = TextBox4.Text;
string clas = TextBox5.Text;
int marks = Convert.ToInt32(TextBox6.Text);
string grade = TextBox7.Text;
cmd.Parameters.Add(new SqlParameter("@stud_id", studid));
cmd.Parameters.Add(new SqlParameter("@name", name));
cmd.Parameters.Add(new SqlParameter("@age", age));
cmd.Parameters.Add(new SqlParameter("@school", school));
cmd.Parameters.Add(new SqlParameter("@class", clas));
cmd.Parameters.Add(new SqlParameter("@marks", marks));
cmd.Parameters.Add(new SqlParameter("@grade", grade));
cmd.ExecuteNonQuery();
conn.Close();
}发布于 2013-12-12 02:25:54
您需要做的是:
cmd.Connection = conn;在执行查询之前。它需要一个连接来执行。
您还可以将其重构为:
SqlCommand cmd = new SqlCommand("student", conn);
cmd.CommandType = CommandType.StoredProcedure;而不是:
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "student";
cmd.Connection = conn;该重载通过构造函数设置CommandText和Connection属性。
您还需要将所有这些ADO.NET对象包装在using语句中。我在blog post of mine上详细解释了这一点。
https://stackoverflow.com/questions/20527064
复制相似问题