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 仍須在資料庫層拼接,注入風險轉移而未消除。
BuildQuery() 產生 SQL 字串,或 BuildCommand() 產生 DbCommand 直接執行。本系列將逐步展示各項核心功能實作。