帶參數的 C# 儲存程序執行:綜合指南
預存程序提供了一種健全且高效的方法,用於在 C# 應用程式中執行資料庫操作,例如插入、更新和刪除。 與直接執行 SQL 命令相比,這種方法具有效能優勢並增強了模組化性。本教學課程示範如何使用 C# 呼叫接受參數的預存程序。
理解預存程序
假設您已經定義了一個預存程序 sp_Add_Contact
,它接受兩個參數:@FirstName
和 @LastName
。 此過程會將新的聯絡人記錄插入您的資料庫中。
建立資料庫連線
先建立一個 SqlConnection
物件來建立與資料庫的連線。此連接將在整個過程中使用。
<code class="language-csharp">using (SqlConnection con = new SqlConnection(dc.Con)) { // Database operations will be performed within this block }</code>
準備 SqlCommand 物件
接下來,實例化一個 SqlCommand
物件來表示 sp_Add_Contact
預存程序。 至關重要的是,將 CommandType
屬性設為 StoredProcedure
以指示您正在使用預存程序,而不是直接 SQL 查詢。
<code class="language-csharp">using (SqlCommand cmd = new SqlCommand("sp_Add_contact", con)) { cmd.CommandType = CommandType.StoredProcedure; // Parameter additions and execution will occur here }</code>
新增參數
使用 cmd
方法將輸入參數新增至 Parameters.Add
物件。指定參數名稱、資料類型 (SqlDbType
),並從應用程式的使用者介面控制項指派值。
<code class="language-csharp">cmd.Parameters.Add("@FirstName", SqlDbType.VarChar).Value = txtFirstName.Text; cmd.Parameters.Add("@LastName", SqlDbType.VarChar).Value = txtLastName.Text;</code>
執行預存程序
定義參數後,預存程序就可以執行了。 使用 ExecuteNonQuery
方法將命令傳送到資料庫並套用變更。
<code class="language-csharp">con.Open(); cmd.ExecuteNonQuery(); con.Close();</code>
執行後刷新資料
成功執行預存程序後,您可能需要刷新應用程式中顯示的資料。 對 Clear
使用 Fill
和 DataTable
操作來反映更新的資料庫狀態。
<code class="language-csharp">dt.Clear(); da.Fill(dt);</code>
以上是如何從 C# 呼叫帶參數的預存程序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!