Call a stored procedure with parameter in c#

前端 未结 7 820
闹比i
闹比i 2020-11-22 16:16

I can do a delete, insert and update in my program and I try to do an insert by call a created stored procedure from my database.

This a button insert I make work

7条回答
  •  有刺的猬
    2020-11-22 16:52

    It's pretty much the same as running a query. In your original code you are creating a command object, putting it in the cmd variable, and never use it. Here, however, you will use that instead of da.InsertCommand.

    Also, use a using for all disposable objects, so that you are sure that they are disposed properly:

    private void button1_Click(object sender, EventArgs e) {
      using (SqlConnection con = new SqlConnection(dc.Con)) {
        using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) {
          cmd.CommandType = CommandType.StoredProcedure;
    
          cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
          cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;
    
          con.Open();
          cmd.ExecuteNonQuery();
        }
      }
    }
    

提交回复
热议问题