让燕子飞的博客

导航

如何使用参数化查询防止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注入漏洞

posted on 2011-02-27 10:49  让燕子飞  阅读(659)  评论(0编辑  收藏  举报