首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> 關於C語言

C# 建立複雜靈活 SQL 查詢實戰(一)

     編輯:關於C語言

傳統字串拼接的痛點


string sql = "SELECT TOP " + maxRecords + " * FROM Customers ";
string where = "WHERE ";
if (txtCompany.Text.Length > 0) {
    sql += where + "CompanyName LIKE '" + txtCompany.Text + "%' ";
    where = "AND ";
}
if (txtCity.Text.Length > 0) {
    sql += where + "City LIKE '" + txtCity.Text + "%' ";
    where = "AND ";
}
if (cboCountry.SelectedItem != null) {
    sql += where + "Country = '" + cboCountry.SelectedItem + "' ";
}

缺點:難讀、易錯、極高 SQL Injection 風險、維護困難。

為何存儲程序非銀彈

動態 SQL 仍須在資料庫層拼接,注入風險轉移而未消除。

SelectQueryBuilder 解決方案

  • 流暢介面(Fluent API)建構查詢結構。
  • 自動參數化,徹底阻擋注入。
  • 支援 BuildQuery() 產生 SQL 字串,或 BuildCommand() 產生 DbCommand 直接執行。
  • 涵蓋 SELECT、INSERT、UPDATE、DELETE、JOIN、GROUP BY、巢狀 WHERE 等完整功能。

本系列將逐步展示各項核心功能實作。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved