萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 電腦基礎知識 >  >> 健康知識

如何撰寫高效、安全的 SQL 查詢程式碼:參數化指令防注入

問題程式碼分析 (C#)

string insertstr = "insert into userinfo(name,password,email,phone,mobile,post,address) VALUES('";
insertstr += this._name.Trim() + "','";
insertstr += this._password.Trim() + "','";
insertstr += this._email.Trim() + "','";
insertstr += this._phone.Trim() + "','";
insertstr += this._mobile.Trim() + "','";
insertstr += this._post.Trim() + "','";
insertstr += this._address.Trim() + "')";

三大缺失

  1. 效率低: 大量字串串接與多餘 Trim() 消耗資源。
  2. 正確性脆弱: 單引號即可導致語法錯誤拋出例外。
  3. 安全性漏洞: 經典 SQL Injection 攻擊面,攻擊者可注入 xp_cmdshell 等危險指令。

正確寫法:參數化指令

string strSql = "INSERT INTO SomeTable (c1, c2, c3, ...) VALUES (@c1, @c2, @c3, ...)";
SqlCommand myCommand = new SqlCommand(strSql, myConn);
try {
    myCommand.Parameters.Add(new SqlParameter("@c1", SqlDbType.VarChar, 20));
    myCommand.Parameters["@c1"].Value = this._Name;
    // 依此類推加入所有參數
}
catch { /* 例外處理 */ }

參數化優勢

  • 效能: 預編譯执行計畫可重用,避免重複解析編譯。
  • 安全: 參數值永遠視為資料而非程式碼,徹底阻擋 SQL Injection;型別與長度驗證自動攔截非法字元。
  • 可維護性: SQL 邏輯與資料分離,程式碼清晰易讀。

告別字串拼接,參數化查詢是專業開發者的基本功。

copyright © 萬盛學電腦網 all rights reserved