1

在 Microsoft Window 应用程序中,我在 app.config 文件中编写连接代码,当我在 winforms 中访问时,它给出了错误,请你帮帮我。

 private void btnInsert_Click(object sender, EventArgs e)
 {
     SqlConnection con = new SqlConnection(ConfigurationManager.AppSettings["mycon"]);

     cmd = new SqlCommand("USP_Insert_Students", con );
     cmd.CommandType = CommandType.StoredProcedure; 
     con.Open();

     cmd.Parameters.AddWithValue("@Stname", txtStname.Text);
     cmd.Parameters.AddWithValue("@class", txtClass.Text);
     cmd.Parameters.AddWithValue("@Section", txtSection.Text);
     cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
     cmd.Parameters.AddWithValue("@states", cmdStates.SelectedText.ToString());
     cmd.ExecuteNonQuery();
    }
4

1 回答 1

2

你的错误是:在mycon里面定义了<connectionStrings>- 但你试图从.AppSettings!

那永远都行不通...

你需要ConfigurationManager.ConnectionStrings["mycon"].ConnectionString改用。

试试这个代码:

private void btnInsert_Click(object sender, EventArgs e)
{
     string connectionString = ConfigurationManager.ConnectionStrings["mycon"].ConnectionString;

     using(SqlConnection con = new SqlConnection(connectionString))
     using(SqlCommand cmd = new SqlCommand("dbo.USP_Insert_Students", con))
     {
         cmd.CommandType = CommandType.StoredProcedure; 

         cmd.Parameters.AddWithValue("@Stname", txtStname.Text);
         cmd.Parameters.AddWithValue("@class", txtClass.Text);
         cmd.Parameters.AddWithValue("@Section", txtSection.Text);
         cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
         cmd.Parameters.AddWithValue("@states", cmdStates.SelectedText.ToString());

         con.Open();
         cmd.ExecuteNonQuery();
         con.Close();        
     }
}
于 2012-06-08T11:31:43.750 回答