1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.Linq; 7 using System.Text; 8 using System.Windows.Forms; 9 using System.Data.SqlClient; 10 11 12 namespace sql注入 13 { 14 public partial class Form1 : Form 15 { 16 public Form1() 17 { 18 InitializeComponent(); 19 } 20 21 private void btnLogin_Click(object sender, EventArgs e) 22 { 23 object obj; 24 //Data Source=.;Initial Catalog=mysql;Integrated Security=True 25 string str = "Data Source =.;Initial Catalog = mysql; Integrated Security = True; "; 26 //下面这种字符串拼接的方式会被 xx' or 1=1 -- 的用户名给注入,所以不能使用 27 //string sql = string.Format("select count(*) from users where name = '{0}' and password = '{1}'",txtName.Text,txtPwd.Text); 28 //使用参数的方法可以避免注入 29 string sql = "select count(*) from users where name = @name and password = @password"; 30 using (SqlConnection con = new SqlConnection(str)) 31 { 32 using (SqlCommand cmd = new SqlCommand(sql, con)) 33 { 34 con.Open(); 35 //cmd使用参数 36 cmd.Parameters.AddWithValue("@name", txtName.Text); 37 cmd.Parameters.AddWithValue("@password", txtPwd.Text); 38 obj = cmd.ExecuteScalar(); 39 if (Convert.ToInt32(obj) > 0) 40 { 41 MessageBox.Show("登录成功"); 42 } 43 else 44 { 45 MessageBox.Show("登录失败"); 46 } 47 48 } 49 } 50 51 52 } 53 } 54 }