2013-12-11 44 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上詳細解釋它。

相關問題