ADO.NET復習總結(3)--參數化SQL語句
阿新 • • 發佈:2017-12-22
輸入 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;View Codeusing System.Data.SqlClient; namespace WindowsFormsApplication2 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { using (SqlConnection conn =newSqlConnection("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()); } } } }
數據庫為:
註意:運行代碼為結果為
數據庫中執行一遍代碼:
結果執行正確,沒有問題、
但是請看執行下面查詢 (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=‘‘‘--底下的代碼
ADO.NET復習總結(3)--參數化SQL語句