参数化防止注入
来源:互联网 发布:企业淘宝开店流程步骤 编辑:程序博客网 时间:2024/06/11 17:31
用到数据库 总逃不过要参数化防止注入 因为有些程序员代码写的简单不完善就给了 一些人钻漏洞的机会 有些还好只是进入你的数据库 有些就恶意篡改你的内容 这就自认倒霉了
具体如何防止 为何防止 我就不贴了 百度一大堆 我就粘贴一下两个参数化防止注入的方法
方法一 :常用的 当数据库内容不多的时候 (推荐)
string strsql = "insert into Student(Name,Gender,Banji,Student_ID,Phone,QQ,Describe,Time) values (@Name,@Gender,@Banji,@Student_ID,@Phone,@QQ,@Describe,@Time)"; SqlParameter[] paras = { new SqlParameter("@Name",name), new SqlParameter("@Gender",gender), new SqlParameter("@Banji",banji), new SqlParameter("@Student_ID",studentid), new SqlParameter("@Phone",phone), new SqlParameter("@QQ",qq), new SqlParameter("@Describe",describe), new SqlParameter("@Time",time) }; /// <summary> /// 对连接执行 Transact-SQL 语句并返回受影响的行数。错误返回-1 /// </summary> /// <param name="sqlstr"></param> /// <param name="para"></param> /// <returns></returns> public bool executeSql(string sqlstr, SqlParameter[] para ) { int i = -1; conn.Open(); SqlCommand sc = new SqlCommand(sqlstr, conn); try { foreach (SqlParameter item in para) { sc.Parameters.Add(item); } i = sc.ExecuteNonQuery(); } catch (Exception ex) { Console.WriteLine(ex.Message); } finally { sc.Dispose(); } return i > 0; }
方法二:
使用临时表实现(也可以使用表变量性能上可能会更加好些),写法实现上比较繁琐些,
可以根据需要写个通用的where in临时表查询的方法,以供不时之需,个人比较推崇这种写法,
能够使查询计划得到复用而且对索引也能有效的利用,不过由于需要创建临时表,会带来额外的IO开销,
若查询频率很高,每次的数据不多时还是建议使用方案3,
若查询数据条数较多,尤其是上千条甚至上万条时,强烈建议使用此方案,可以带来巨大的性能提升(强烈推荐)
using (SqlConnection conn = new SqlConnection(connectionString)){ conn.Open(); SqlCommand comm = new SqlCommand(); comm.Connection = conn; string sql = @" declare @Temp_Variable varchar(max) create table #Temp_Table(Item varchar(max)) while(LEN(@Temp_Array) > 0) begin if(CHARINDEX(',',@Temp_Array) = 0) begin set @Temp_Variable = @Temp_Array set @Temp_Array = '' end else begin set @Temp_Variable = LEFT(@Temp_Array,CHARINDEX(',',@Temp_Array)-1) set @Temp_Array = RIGHT(@Temp_Array,LEN(@Temp_Array)-LEN(@Temp_Variable)-1) end insert into #Temp_Table(Item) values(@Temp_Variable) end select * from Users(nolock) where exists(select 1 from #Temp_Table(nolock) where #Temp_Table.Item=Users.UserID) drop table #Temp_Table"; comm.CommandText = sql; comm.Parameters.Add(new SqlParameter("@Temp_Array", SqlDbType.VarChar, -1) { Value = "1,2,3,4" }); comm.ExecuteNonQuery();}
第二种 我自己还没太懂 毕竟学的比较浅
阅读全文
0 0
- 参数化防止注入
- 防止SQL注入的参数化方法
- 参数化查询----防止SQL注入
- 防止sql注入的参数化查询
- [牛腩]参数化查询防止SQL注入
- 参数化登陆防止SQL注入攻击
- 参数化命令(防止SQL注入)
- sql参数绑定防止注入
- sql参数绑定防止注入
- 使用参数化查询防止SQL注入漏洞
- 使用参数化查询防止SQL注入漏洞
- C#参数化查询数据库、防止被注入
- C#的SQL参数化查询 防止SQL注入
- 参数化SQL语句,防止SQL注入漏洞攻击
- 参数化查询为什么能够防止SQL注入
- 参数化查询为什么能够防止SQL注入
- 防止SQL注入-参数化SQL例代码asp.net
- 参数化查询为什么能够防止SQL注入
- 拓扑排序核心代码
- 字符输出流(写)常用方法2
- 统一配置服务——spring cloud config
- 干货分享丨如何恢复Linux下误删etc目录数据
- 数据结构 直接插入排序
- 参数化防止注入
- Linux中静态库和共享库的制作方法
- EditTextt如何设置获取焦点后,光标在末尾的解决办法
- CaptureMouse/CaptureStylus 可能会失败
- "=="和equals方法究竟有什么区别?
- day01
- java数组
- RxJava:walfud 彻底搞懂 RxJava 系列 笔记
- 数据库的备份