- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.Configuration;
- using System.Data.SqlClient;
- namespace sql注入
- {
- class Program
- {
- static void Main(string[] args)
- {
- string dataDir = AppDomain.CurrentDomain.BaseDirectory;
- if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\"))
- {
- dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName;
- AppDomain.CurrentDomain.SetData("DataDirectory", dataDir);
- }
- Console.WriteLine("请输入用户名:");
- string userName = Console.ReadLine();
- Console.WriteLine("请输入密码:");
- string passWord = Console.ReadLine();
- string connStr = ConfigurationManager.ConnectionStrings["connStr"].ConnectionString;
- using (SqlConnection conn = new SqlConnection(connStr))
- {
- conn.Open();
- using (SqlCommand cmd = conn.CreateCommand())
- {
- //cmd.CommandText = "select * from T_Users where FName='"+userName+"' and FPass='"+passWord+"'";//拼接字符串容易出现sql注入,如果用户输入admin,密码输入1' or '1'='1也会提示登录成功
- cmd.CommandText = "select * from T_Users where FName=@name and FPass=@password";//使用参数查询的时候会把参数当作一项去数据表中做比较,而不是拼接字符串
- cmd.Parameters.Add(new SqlParameter("name",userName));
- cmd.Parameters.Add(new SqlParameter("password", passWord));
- using (SqlDataReader reader = cmd.ExecuteReader())
- {
- if (reader.Read())
- {
- Console.WriteLine("登陆成功");
- }
- else
- {
- Console.WriteLine("用户名或密码错误");
- }
- }
- }
- }
- Console.ReadKey();
- }
- }
- }
复制代码 |