2013-12-11 45 views
1

1.ExecuteNonQuery:Connection属性尚未初始化” 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(); 
} 
+0

有人帮我出来 – user3045190

+0

你没有告诉'cmd'使用哪个连接。将它作为参数传递给'new SqlCommand()' – cgTag

回答

5

你需要做的:

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; 

即超载套通过构造的CommandTextConnection性质。

您还需要将所有这些ADO.NET对象包装在using语句中。我在blog post of mine上详细解释它。

相关问题