You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用SqlDataReader实现SQL Server登录页时遇语法错误求助

问题解决:SqlDataReader触发SQL语法错误

你的错误根源是SQL语句语法错误,问题出在登录按钮点击事件里的查询语句:

原代码里的SQL写法:

SqlCommand cmd = new SqlCommand("SELECT * FROM tbl_users WHERE Username =('" + txtUsername.Text + "','" + txtPassword.Text + "')",con) ;

这里把用户名和密码塞进同一个括号里,SQL会判定为非法语法——你原本想同时匹配用户名和密码,正确逻辑应该是用AND连接两个独立条件,而非把两个值赋值给单个字段。

另外,直接拼接用户输入到SQL语句里会引发SQL注入攻击,这是严重的安全漏洞,必须用参数化查询修复。

修改后的完整按钮事件代码

private void button1_Click(object sender, EventArgs e)
{
    // 用using自动释放连接资源,无需手动Close
    using (SqlConnection con = new SqlConnection("Data Source=CONSOLE-03;Initial Catalog=db_users;Integrated Security=True"))
    {
        con.Open();
        // 参数化SQL语句,避免语法错误和注入风险
        string sql = "SELECT * FROM tbl_users WHERE Username = @Username AND Password = @Password";
        SqlCommand cmd = new SqlCommand(sql, con);
        
        // 绑定参数,对应SQL中的@占位符
        cmd.Parameters.AddWithValue("@Username", txtUsername.Text);
        cmd.Parameters.AddWithValue("@Password", txtPassword.Text);

        using (SqlDataReader dr = cmd.ExecuteReader())
        {
            if (dr.Read())
            {
                new Dashboard().Show();
                this.Hide();
            }
            else
            {
                MessageBox.Show("用户名或密码错误,请重试", "登录失败", MessageBoxButtons.OK, MessageBoxIcon.Error);
                txtUsername.Text = "";
                txtPassword.Text = "";
                txtUsername.Focus();
            }
        }
    }
}

核心修改说明

  • 修正SQL条件逻辑:用AND同时校验用户名和密码,符合业务需求
  • 替换字符串拼接为参数化查询,彻底杜绝SQL注入风险
  • 用using包裹数据库连接和数据阅读器,自动释放资源,避免连接泄漏

内容的提问来源于stack exchange,提问作者Jeffry Vergara

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 04:26:05