参数化登陆防止SQL注入攻击

12 篇文章 0 订阅
 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("登录失败");
            }
            //连接数据库
        }
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值