1. 程式人生 > >ADO.NET復習總結(3)--參數化SQL語句

ADO.NET復習總結(3)--參數化SQL語句

輸入 net connect varchar 學生表 sap style text 執行過程

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

技術分享圖片

ADO.NET復習總結(3)--參數化SQL語句