防止SQL注入的3个方法
//方法一:参数化查询。缺点:增大数据库的压力 string ConnectionString="";//数据库连接字串 string CustomerID = string.Empty; string CompanyName =string.Empty; string Address =string.Empty; using (SqlConnection cn = new SqlConnection(ConnectionString)) { cn.Open(); SqlCommand cmd = new SqlCommand("insert into Customers(CustomerID,CompanyName,Address) values(@CustomerID,@CompanyName,@Address)", cn); //cmd.Parameters.Add(new SqlParameter("@CustomerID", CustomerID)); 不会去与数据库匹配 cmd.Parameters.Add("@CustomerID", SqlDbType.NChar, 5, CustomerID);//这种设置的数据类型,长度都必须与数据库字段一致 cmd.Parameters.Add("@CompanyName", SqlDbType.NVarChar, 40, CompanyName); cmd.Parameters.Add("@Address", SqlDbType.NVarChar, 60, Address); cmd.ExecuteNonQuery(); cn.Close(); } //方法二:过滤输入的信息,检查是否存在危险字符。不必连接数据库 /// <summary> /// 检查输入的数据 是否存在危险字符 /// </summary> /// <param name="sUser"></param> /// <param name="sPwd"></param> /// <returns>返回一个bool值</returns> public bool CheckData(string sUser, string sPwd) { if (sUser.IndexOf("'") != -1 || sPwd.IndexOf("%") != -1) { return false; } return true; } //方法三:使用存储过程(简单代码) string ConnectionString = "";//数据库连接字串 string CustomerID = string.Empty; string CompanyName = string.Empty; string Address = string.Empty; using (SqlConnection cn = new SqlConnection(ConnectionString)) { cn.Open(); string Sql = "InsertUserProc";//存储过程名 SqlCommand cmd = new SqlCommand(Sql,cn); cmd.CommandType = CommandType.StoredProcedure; cmd.ExecuteNonQuery(); cn.Close(); }