ADO.NET 学习笔记(七) SQL注入漏洞与参数化查询

登录界面

 1 static void Main(string[] args)

 2 {

 3   string dataDir = AppDomain.CurrentDomain.BaseDirectory;

 4   if (dataDir.EndsWith(@"\bin\Debug\")||dataDir.EndsWith(@"\bin\Release\"))

 5   {

 6     dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;

 7     AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);

 8   }

 9 

10   Console.WriteLine("请输入用户名");

11   string userName = Console.ReadLine();

12 

13   Console.WriteLine("请输入密码");

14   string passWord = Console.ReadLine();

15 

16   using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))

17   {

18     conn.Open();

19     using (SqlCommand cmd = conn.CreateCommand())

20     {

21       cmd.CommandText="select count(*) from T_User where FUserName='"+userName+"' and FPassword='"+passWord+"'";

22       int i=Convert.ToInt32(cmd.ExecuteScalar());

23       if(i>0)

24       {

25         Console.WriteLine("登录成功");

26         Console.ReadKey();

27       }

28       else

29       {

30         Console.WriteLine("用户名或密码错误");

31         Console.ReadKey();

32       }

33     }

34   }

35 }

这种写法存在SQL注入漏洞例如:密码输入1' or '1'='1
也是可以登录通过的
select count(*) from T_User where FUserName='admin' and FPassword='1' or '1'='1'
1=1永远是真

解决这个问题的办法是使用参数化查询

cmd.CommandText="select count(*) from T_User where FUserName=@UN and FPassword=@P";
cmd.Parameters.Add(new SqlParameter("UN",userName));
cmd.Parameters.Add(new SqlParameter("P",passWord));

Parameters是一个集合,可以添加SqlParameter对象
SqlParameter构造函数有两个参数:参数名,参数值

 1 static void Main(string[] args)

 2 {

 3   string dataDir = AppDomain.CurrentDomain.BaseDirectory;

 4   if (dataDir.EndsWith(@"\bin\Debug\")||dataDir.EndsWith(@"\bin\Release\"))

 5   {

 6     dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;

 7     AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);

 8   }

 9 

10   Console.WriteLine("请输入用户名");

11   string userName = Console.ReadLine();

12 

13   Console.WriteLine("请输入密码");

14   string passWord = Console.ReadLine();

15 

16   using (SqlConnection conn = new SqlConnection(@"Data Source=.\SQLEXPRESS;AttachDBFilename=|DataDirectory|\Database1.mdf;Integrated Security=True;User Instance=True"))

17   {

18     conn.Open();

19     using (SqlCommand cmd = conn.CreateCommand())

20     {

21       cmd.CommandText="select count(*) from T_User where FUserName=@UN and FPassword=@P";

22       cmd.Parameters.Add(new SqlParameter("UN",userName));

23       cmd.Parameters.Add(new SqlParameter("P",passWord));

24       int i=Convert.ToInt32(cmd.ExecuteScalar());

25       if(i>0)

26       {

27         Console.WriteLine("登录成功");

28         Console.ReadKey();

29       }

30       else

31       {

32         Console.WriteLine("用户名或密码错误");

33         Console.ReadKey();

34       }

35     }

36   }

37 }

 

你可能感兴趣的:(sql注入)