当前位置:Gxlcms > 数据库问题 > ADO.NET复习总结(3)--参数化SQL语句

ADO.NET复习总结(3)--参数化SQL语句

时间:2021-07-01 10:21:17 帮助过:13人阅读

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 Nselect count(*) from userinfo where username=@name,N@name nvarchar(16),@name=Na‘‘ or 1=1 or 1=‘‘‘--底下的代码

技术分享图片

 

ADO.NET复习总结(3)--参数化SQL语句

标签:执行   server   window   space   width   click   height   client   box   

人气教程排行