天天看点

SqlParameter防SQL注入的方法

1、 SqlParameter 构造函数

SqlParameter(String, SqlDbType, Int32,ParameterDirection, Byte, Byte, String, DataRowVersion, Boolean, Object,String, String, String),其参数分别代表该类使用参数名、参数的类型、参数的长度、方向、精度、小数位数、源列名称、DataRowVersion 值之一、用于源列映射的布尔值、SqlParameter 的值、此 XML 实例的架构集合所在的数据库的名称、此 XML 实例的架构集合所在的关系架构以及此参数的架构集合的名称。

2、  SqlParameter的应用

List<CommandInfo> cmd = new List<CommandInfo>();
for (int i = 0; i < dt.Rows.Count; i++)
{
  StringBuilder strSqlConfig = new StringBuilder();
  strSqlConfig.Append("insert into CMB_UpdateStatus_OnlineRecord(OnlineRecordTicketNo,SiemensEmployeeName)"
      + " values(@Tno,@Name) ");
  try
    {
       SqlParameter[] paraConfig ={ new SqlParameter("@Tno", SqlDbType.NVarChar, 10),
                                   new SqlParameter("@Name", SqlDbType.NVarChar,50)};
       paraConfig[0].Value = dt.Rows[i]["机票号"].ToString();
        paraConfig[1].Value = dt.Rows[i]["姓名"].ToString();
       cmd.Add(new CommandInfo(strSqlConfig.ToString(), paraConfig));
     }
   catch (Exception ex)
    {
        MessageBox.Show("excel写入数据库时发生错误:{0}", ex.Message);
        return;
     }
    }
  Hippo.ExecuteSqlTran(cmd);
           

3、 SqlParameter的基本原理是执行计划重用。即对注入后的SQL语句重新进行了编译,重新执行了语法解析。

参考:https://www.2cto.com/article/201402/281712.html