sql 防注入漏洞
2015-09-19 15:42
337 查看
一、为了防止sql 注入漏洞,应使用sql参数
以下代码 当 textBox1.Text 是 1' or '1'='1 时就会产生 sql 注入漏洞
修改代码:使用sql参数可以防止漏洞
注释:凡是以字符串拼接的sql语句都存在漏洞,包括StringBuilder 等,要防止漏洞必须使用sql参数
凡是继承 IDisposable 接口的类 ,做好使用 using ,这样可以确保最后释放资源,
如果使用try catch finally 难免最后忘记关闭链接,手动释放资源问题
以下代码 当 textBox1.Text 是 1' or '1'='1 时就会产生 sql 注入漏洞
private void button1_Click(object sender, EventArgs e) { using(SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=ZTest;User Id=sa;Password=1")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { // 输入 1' or '1'='1 会造成sql 注入漏洞 cmd.CommandText = "select age from Student where name='" + textBox1.Text + "'"; using (SqlDataReader read = cmd.ExecuteReader()) { while (read.Read()) { // GetInt32 获得的是int 类型 // GetInt64 获得的是long 类型 int age = read.GetInt32(0); } } } } }
修改代码:使用sql参数可以防止漏洞
private void button1_Click(object sender, EventArgs e) { using(SqlConnection conn = new SqlConnection("Data Source=.;Initial Catalog=ZTest;User Id=sa;Password=1")) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) {
cmd.CommandText = "select age from Student where name=@name1"; //cmd.Parameters.Add("@name1", textBox1.Text); //cmd.Parameters.AddWithValue("@name1", textBox1.Text); cmd.Parameters.Add(new SqlParameter("@name1", textBox1.Text)); using (SqlDataReader read = cmd.ExecuteReader()) { while (read.Read()) { // GetInt32 获得的是int 类型 // GetInt64 获得的是long 类型 int age = read.GetInt32(0); } } } } }
注释:凡是以字符串拼接的sql语句都存在漏洞,包括StringBuilder 等,要防止漏洞必须使用sql参数
凡是继承 IDisposable 接口的类 ,做好使用 using ,这样可以确保最后释放资源,
如果使用try catch finally 难免最后忘记关闭链接,手动释放资源问题
相关文章推荐
- 你知道数据库索引的工作原理吗?
- Table './mysql/proc' is marked as crashed and should be repaired 解决方法
- 浅谈PL/SQL语言基础
- oracle语言基础
- vs2010连接远程数据库出现程序崩溃
- sql 数据类型和 .net/C#的类型对应关系
- 浅谈oracle事务
- ubuntu安装mysql可视化工具MySQL-workbench及简单操作
- [Mysql variables] 解析sql_mode
- output sql语句大全
- Oracle 查询前10条记录及分页查询(第五条到第十条记录)
- MongoDb使用
- 【技术篇】SQL的四种连接-左外连接、右外连接、内连接、全连接
- [iOS][更新]iOS开发数据库操作之SQLite及Mysql操作实例
- MySql数据类型
- Can't connect to local MySQL server through socket '/var/lib/mysql/mysql.soc
- ubuntu安装mysql及简单操作
- redis sentinel 集群
- mysql 5.6 存储过程+事务+游标+错误异常抛出+日志写入
- MySQL数据库备份