参数查询,拼接SQL会造成注入漏洞攻击。
1.cmd.CommandText = "select Age from T_Student where Name='战三'";
2.cmd.CommandText = "select Age from T_Student where Name='"+txtName.Text+"'";
输入1'or'1='1会造成SQl输入漏洞'3.string t_name = txtName.Text; cmd.CommandText = "select age from T_Student where Name='"+t_name+"'";SQL语句使用@UserName表示“此处用参数代替”,向sqlCommand的Parameters中添加参数,格式如下:
1.cmd.CommandText = "select Age from T_Student where Name=@Name";
2.cmd.Parameters.AddWithValue("@Name", txtName.Text);或者 cmd.Parameters.Add(new SqlParameter("@Name", txtName.Text));实例的代码为如下:(在窗体中拖动一个TextBox和button按钮,并为按钮添加click事件)
1 private void btnSearch_Click(object sender, RoutedEventArgs e) 2 { 3 4 5 //数据库连接字符串,使用using(){}格式会在{}后释放资源 6 using (SqlConnection conn = new SqlConnection("Data Source=.; Initial Catalog=T_Test; User ID=sa ;Password=123456")) 7 { 8 conn.Open();//打开数据库 9 using (SqlCommand cmd = conn.CreateCommand())10 {11 //1.cmd.CommandText = "select Age from T_Student where Name='战三'";12 //2.cmd.CommandText = "select Age from T_Student where Name='"+txtName.Text+"'";13 //输入1'or'1='1会造成SQl输入漏洞'14 //3.string t_name = txtName.Text;15 // cmd.CommandText = "select age from T_Student where Name='"+t_name+"'";16 //安全做法如下,参数不能替换表名,字段名和Select的关键字等17 cmd.CommandText = "select Age from T_Student where Name=@Name";18 // cmd.Parameters.AddWithValue("@Name", txtName.Text);19 cmd.Parameters.Add(new SqlParameter("@Name", txtName.Text));20 21 22 using (SqlDataReader reader = cmd.ExecuteReader())//查询结果是存放在数据库中的,不占用本地电脑系统内存23 {24 while (reader.Read())//初始指针指向第一条数据之前,每调用一次Read指针下一一条,只要没有指到最后一条之后就返回true25 { //GetInt64获得的是long类型(在数据库中是bigint类型)26 int age = reader.GetInt32(0);//GetString(0)中的0表示读取的是第0列的数据。取决于在查询结果中是第0列。27 MessageBox.Show(age.ToString());//reader的GetString()GetInt32()等方法只接受整数参数也就是序号,用GetOrdinal(根据列名得到序号28 }29 }30 }31 }32 }