Home > Backend Development > C++ > How to Call Stored Procedures with Parameters in C#?

How to Call Stored Procedures with Parameters in C#?

DDD
Release: 2025-01-23 12:46:11
Original
244 people have browsed it

How to Call Stored Procedures with Parameters in C#?

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>
Copy after login

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>
Copy after login

Finally, execute the stored procedure:

<code class="language-csharp">            con.Open();
            cmd.ExecuteNonQuery();
            con.Close(); // explicitly close the connection
        }
    }
}</code>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template