ADO.NET复习总结(3)--参数化SQL语句--防止sql注入式攻击

1、SQL 注入

2、使用参数化的方式,可以有效防止SQL注入,使用类parameter的实现类SqlParameter

      Command的属性parameters是一个参数集合。

3、举例<查询学生表学生个数>

代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn =new SqlConnection("server=.;database=dbtest;uid=sa;pwd=123") )
            {
                string sql = "select Count(*) from userinfo where username='" + textBox1.Text + "'   ";
                SqlCommand cmd = new SqlCommand(sql,conn);
                conn.Open();
                int i = Convert.ToInt32(cmd.ExecuteScalar());
                MessageBox.Show(i.ToString());
            }
        }
    }
}
View Code

数据库为:

注意:运行代码为结果为

 数据库中执行一遍代码:

 结果执行正确,没有问题、

但是请看执行下面查询 (sql注入原理:攻击数据库的一种方式):

查询框中输入:

a' or 1=1 or 1='

 

在数据库中的代码为(加单引号):

select Count(*) from userinfo where username='a' or 1=1 or 1=''--这句永远为true

4、实行参数化

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsFormsApplication2
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            using (SqlConnection conn =new SqlConnection("server=.;database=dbtest;uid=sa;pwd=123") )
            {
               // string sql = "select Count(*) from userinfo where username='" + textBox1.Text + "'   ";
                string sql = "select count(*) from userinfo where username=@name";//参数化
                SqlCommand cmd = new SqlCommand(sql,conn);
                //加参数:cmd的parameters属性,一个参数用add方法
                cmd.Parameters.Add(
                    new SqlParameter("@name", textBox1.Text)
                    );
                conn.Open();
                int i = Convert.ToInt32(cmd.ExecuteScalar());
                MessageBox.Show(i.ToString());
            }
        }
    }
}
View Code

参数化语句执行过程:

(1)打开数据库工具->Profier工具(数据库分析监测工具)

(2)执行代码:输入a' or 1=1 or 1='

点击button后

 

(3)然后看下Profiler

exec sp_executesql N'select count(*) from userinfo where username=@name',N'@name nvarchar(16)',@name=N'a'' or 1=1 or 1='''--底下的代码

5、 PPT理论知识

(1)SQL注入漏洞攻击

(2)查询参数

原文地址:https://www.cnblogs.com/mhq-martin/p/8086930.html