- Dapper 原生支援
IN()查詢,無需手動拼接逗號字串。 - 規則:參數傳入陣列 / List 集合,Dapper 會自動展開產生 IN 條件。
- SQL 固定寫法:
WHERE Id IN @ids,不要額外加上括號,錯誤寫法IN (@ids)。 - 優點:全程使用參數化查詢,可避免 SQL 注入風險。
範例
using System.Data;
using MySql.Data.MySqlClient;
using Dapper;
using System.Configuration;
using System.Collections.Generic;
static void Main(string[] args)
{
var connStr = ConfigurationManager.ConnectionStrings["StudentConnection"].ConnectionString;
using (IDbConnection db = new MySqlConnection(connStr))
{
string sql = "SELECT * FROM student WHERE Id IN @ids";
// 支援 int[] 陣列 / List<int>
int[] idArray = {3,4};
List<Student> studentList = db.Query<Student>(
sql,
new { ids = idArray }
).ToList();
}
}Code language: JavaScript (javascript)
兩種參數寫法都可以使用
// 方式1:陣列(原始範例)
new { ids = new int[] {3,4} }
// 方式2:List 集合(專案內較常使用)
new { ids = new List<int> {3,4,5} }Code language: PHP (php)
批次刪除 Delete
string sqlDelete = "DELETE FROM student WHERE Id IN @ids";
int rows = db.Execute(sqlDelete, new { ids = new int[]{2,5} });Code language: JavaScript (javascript)
多條件 IN 查詢
string sql = "SELECT * FROM student WHERE Id IN @ids AND Email IN @emails";
var param = new
{
ids = new int[]{1,2},
emails = new string[]{"a@gmail.com","b@gmail.com"}
};
var list = db.Query<Student>(sql, param).ToList();Code language: PHP (php)
IN 查詢
Previous: Dapper 預存程序
Next: 多陳述式操作