Using Stored Procedures with Parameters in C# Applications
Your application already handles database inserts, updates, and deletes. Now, let's integrate stored procedures to improve data insertion. We'll begin by adding a button to initiate the stored procedure call.
First, create a button click event handler:
<code class="language-csharp">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;</code>
Next, we'll add the parameters required by the stored procedure sp_Add_contact
. This procedure expects @FirstName
and @LastName
as input parameters. We'll map these to text boxes in our application:
<code class="language-csharp"> cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text); cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);</code>
Finally, execute the stored procedure:
<code class="language-csharp"> con.Open(); cmd.ExecuteNonQuery(); con.Close(); // explicitly close the connection } } }</code>
This code is similar to executing standard SQL queries, but utilizes SqlCommand
directly. Unlike data adapters, stored procedures don't necessitate their use. This approach improves database performance and security. The using
statements ensure proper resource management by automatically closing and disposing of the connection and command objects. Note the explicit con.Close()
call added for clarity, although it's handled automatically by the using
statement.
The above is the detailed content of How to Call Stored Procedures with Parameters in C#?. For more information, please follow other related articles on the PHP Chinese website!