如何使用参数化查询防止Sql注入漏洞
原程序如下:
string sqlconString = @"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"; Console.Write("请输入用户名:"); string userName = Console.ReadLine(); Console.Write("请输入密码:"); string password = Console.ReadLine(); using (SqlConnection conn = new SqlConnection(sqlconString)) { conn.Open(); using (SqlCommand cmd = conn.CreateCommand()) { cmd.CommandText = "select count(*) from T_Users where UserName='" + userName + "' and Password='" + password + "'";//sql注入,当密码= 1' or '1'='1 int i = Convert.ToInt32(cmd.ExecuteScalar()); if (i>0) { Console.WriteLine("登入成功"); } else { Console.WriteLine("用户名或密码错误"); } } }
以上代码当用户输入密码为:1' or '1'='1 时,提示登入成功!
所以必须使用参数化查询防止Sql注入漏洞,如下:
使用参数化查询防止Sql注入漏洞