首頁 >後端開發 >C++ >如何在C#中呼叫帶參數的預存程序?

如何在C#中呼叫帶參數的預存程序?

Linda Hamilton
Linda Hamilton原創
2025-01-23 12:52:10280瀏覽

How to Call a Stored Procedure with Parameters in C#?

在C#中呼叫帶參數的預存程序

問題:

如何從我的C#程式碼中呼叫帶參數的預存程序? 我可以使用命令字串執行插入、更新和刪除操作,但不確定如何處理預存程序。

這是我目前的程式碼,它使用命令字串成功插入資料:

<code class="language-csharp">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);
}</code>

解答:

要呼叫帶有參數的預存程序,您可以按照以下步驟操作:

  1. 建立一個SqlCommand對象,並將其CommandType屬性設為CommandType.StoredProcedure。
  2. 使用Parameters集合向SqlCommand物件新增參數。每個參數都應指定其名稱、資料類型和值。
  3. 開啟資料庫連線並執行SqlCommand。

以下更新後的程式碼示範如何使用兩個參數呼叫sp_Add_contact預存程序:

<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;

            cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);
            cmd.Parameters.AddWithValue("@LastName", txtLastName.Text);

            con.Open();
            cmd.ExecuteNonQuery();
        }
    }

    dt.Clear();
    da.Fill(dt);
}</code>

為了提高程式碼的可讀性和可維護性,建議使用AddWithValue方法新增參數,它會自動推斷參數的資料類型。 請確保你的預存程序 sp_Add_contact 確實存在且參數名稱與程式碼中的一致。

以上是如何在C#中呼叫帶參數的預存程序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn