- 預存程序(Stored Procedure):事先在資料庫內寫好SQL邏輯,程式直接呼叫執行。
- Dapper呼叫預存程序的重點:設定
CommandType.StoredProcedure。 - 透過匿名類別或實體物件傳入參數,會自動對應預存程序的輸入參數。
- 範例場景:建立MySQL預存程序,依照ID刪除student資料。
MySQL 建立預存程序
-- 建立刪除學生資料的預存程序
CREATE DEFINER=`root`@`localhost` PROCEDURE `Delete_Student_PROC`(IN `id` INT)
BEGIN
DELETE FROM student WHERE Id = id;
ENDCode language: JavaScript (javascript)
IN id int:輸入參數,接收要刪除的主鍵編號- BEGIN ~ END:預存程序的程式主體
DROP PROCEDURE IF EXISTS Delete_Student_PROC;
呼叫預存程序
using System.Data;
using MySql.Data.MySqlClient;
using Dapper;
using System.Configuration;
static void Main(string[] args)
{
var connStr = ConfigurationManager.ConnectionStrings["StudentConnection"].ConnectionString;
using (IDbConnection db = new MySqlConnection(connStr))
{
// 參數說明:
// 第一個引數:預存程序名稱
// 第二個引數:要傳入的參數
// 第三個引數:必須指定命令型別為預存程序
int affectedRows = db.Execute(
"Delete_Student_PROC",
new { id = 2 },
commandType: CommandType.StoredProcedure
);
Console.WriteLine($"受影響資料列數:{affectedRows}");
}
Console.ReadKey();
}Code language: JavaScript (javascript)
有回傳查詢結果的預存程序
如果預存程序用來查詢資料,請使用 .Query<T>()
List<Student> list = db.Query<Student>(
"GetAllStudent_PROC",
null,
commandType: CommandType.StoredProcedure
).ToList();Code language: PHP (php)
- 一般SQL:
commandType: CommandType.Text(預設值,可以省略不寫) - 預存程序:
commandType: CommandType.StoredProcedure(一定要明確指定)
Dapper 預存程序
Previous: Dapper 刪除操作
Next: IN 查詢