數據庫參數化傳遞可以增強數據的安全性,但卻會降低開發效率,為此創建了如下函數以解決這個問題:
public static string PrepareParameter(string sql, out SqlParameter[] cmdParms, params object[] args) { cmdParms = null; if (args != null && args.Length != 0) { string[] argNames = new string[args.Length]; cmdParms = new SqlParameter[args.Length]; string prefix = "arg"; for (int i = 0, c = args.Length; i < c; i++) { string ParameterName = prefix + i; cmdParms[i] = new SqlParameter(); cmdParms[i].ParameterName = ParameterName; cmdParms[i].Value = args[i]; argNames[i] = "@" + ParameterName; } sql = string.Format(sql, argNames); } return sql; }
使用方法如下: