問題:
如何從我的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>
解答:
要呼叫帶有參數的預存程序,您可以按照以下步驟操作:
以下更新後的程式碼示範如何使用兩個參數呼叫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中文網其他相關文章!