SQL動態查詢

  • 199
  • 0
  • 2021-01-05

動態查詢如何新增查詢式

假設查詢選項有以下項目:

  1. 使用者
  2. 性別
  3. 時間
  4. 地區
public void query(string User, int sex, DateTime d, string locate)
{
    string sql = "select * from TestTable where 1 = 1 ";
    if (User != null)
        sql += $"and User = '{User}' ";
    if (sex > 0)
        sql += $"and Sex = '{sex}' ";
    if (d != null)
        sql += $"and Time > '{d.ToString("yyyy-MM-dd hh:mm:ss")}' ";
    if (locate != null)
        sql += $"and Locate = '{locate}'";
}

用這樣判斷的方式就能組成動態查詢的效果,請注意SQL Injection 上訴方法會造成SQL Injection