小编典典

在C#中使用参数调用存储过程

c#

我可以在程序中执行删除,插入和更新操作,并尝试通过从数据库中调用创建的存储过程来进行插入。

这个按钮插入我做得很好。

private void btnAdd_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection(dc.Con);
        SqlCommand cmd = new SqlCommand("Command String", con);

        da.InsertCommand = new SqlCommand("INSERT INTO tblContacts VALUES (@FirstName, @LastName)", con);
        da.InsertCommand.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text;
        da.InsertCommand.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;

        con.Open();
        da.InsertCommand.ExecuteNonQuery();
        con.Close();

        dt.Clear();
        da.Fill(dt);
    }

这是调用名为sp_Add_contact添加联系人的过程的按钮的开始。的两个参数sp_Add_contact(@FirstName,@LastName)。我在Google上搜索了一个很好的例子,但没有发现任何有趣的事情。

private void button1_Click(object sender, EventArgs e)
{
        SqlConnection con = new SqlConnection(dc.Con);
        SqlCommand cmd = new SqlCommand("Command String", con);
        cmd.CommandType = CommandType.StoredProcedure;

        ???

        con.Open();
        da. ???.ExecuteNonQuery();
        con.Close();

        dt.Clear();
        da.Fill(dt);
    }

阅读 491

收藏
2020-05-19

共1个答案

小编典典

它与运行查询几乎相同。在原始代码中,您正在创建一个命令对象,将其放入cmd变量中,并且永远不要使用它。但是,在这里,您将使用而不是da.InsertCommand

另外,using对所有一次性物品都使用A ,以确保正确放置它们:

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();
    }
  }
}
2020-05-19