using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace _01参数化登陆防止SQL注入攻击
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnLogin_Click(object sender, EventArgs e)
{
object obj;
//获取帐号和密码
//准备连接字符串
string str = "Data Source=XY-PC;Initial Catalog=MyItcast;Integrated Security=True";
using (SqlConnection con=new SqlConnection(str))
{
//string sql =string.Format( "select COUNT(*) from UserLogin where UserName='{0}' and UserPwd='{1}'",txtName.Text,txtPwd.Text);//这种会被sql注入攻击
string sql ="select COUNT(*) from UserLogin where UserName=@name and UserPwd=@pwd";
//不是所有的值都要用参数化的方式进行替换,什么时候用参数什么时候不用参数?
//用户输入的 那就用参数
using (SqlCommand cmd=new SqlCommand(sql,con))
{
con.Open();
cmd.Parameters.AddWithValue("@name", txtName.Text);
cmd.Parameters.AddWithValue("@pwd", txtPwd.Text);
obj= cmd.ExecuteScalar();
}
}
if (Convert.ToInt32(obj)>0)
{
MessageBox.Show("登录成功");
}
else
{
MessageBox.Show("登录失败");
}
//连接数据库
}
}
}
参数化登陆防止SQL注入攻击
最新推荐文章于 2023-06-29 11:52:41 发布