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

如何解决WPF开发中System.Data.SqlClient.SqlException:PasswordBox附近语法错误

问题诱因
  • 构造SqlDataAdapter的查询语句时,直接将WPF控件对象txtUsername、password拼接进SQL字符串,没有取控件对应的文本/密码属性。控件对象默认ToString()结果为自身类名,password控件的ToString()结果就是异常里的System.Windows.Controls.PasswordBox,直接拼入SQL后触发语法错误。
  • 拼接的SQL本身存在语法错误:PASSWORD字段和值之间缺少等号,写为PASSWORD' + password + ',正确写法应为PASSWORD = 'xxx'。
  • 此前编写的带参数的SqlCommand完全没有被调用,属于冗余代码,反而使用了风险极高的字符串拼接SQL写法,既容易出现语法问题,还存在SQL注入漏洞。
修复方案

直接删除冗余代码,改用参数化查询完成登录校验即可,修复后代码如下:

private void Button_Click_2(object sender, RoutedEventArgs e)
{
    string mainconn = "Data Source=VCPTCR4PC19\\SQLEXPRESS;Initial Catalog=TASK2;Integrated Security=True";
    // 用using自动释放连接资源,不需要手动调用Close
    using (SqlConnection conn = new SqlConnection(mainconn))
    {
        conn.Open();
        // 参数化查询SQL,避免拼接风险和语法错误
        string sql = "Select Count(*) From USERS Where USER_NAME = @USER_NAME and PASSWORD = @PASSWORD";
        SqlCommand command = new SqlCommand(sql, conn);
        command.Parameters.Add("@USER_NAME", SqlDbType.VarChar).Value = txtUsername.Text;
        command.Parameters.Add("@PASSWORD", SqlDbType.VarChar).Value = HashCode.PassHash(password.Password);
        
        int count = (int)command.ExecuteScalar();
        if (count == 1)                
        {
            this.Hide();
            Modules modules = new Modules();
            modules.ShowDialog();
        }
        else
        {
            MessageBox.Show("Invalid user name or password entered");
        }
    }
}
额外注意
  • 原代码中拼写错误的Invaild、enterd可同步修正为Invalid、entered。
  • 参数化查询是操作数据库的标准写法,既可以避免这类拼接导致的语法错误,也能完全避免SQL注入攻击。

内容的提问来源于stack exchange,提问作者Javian Poonsamy

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 07:06:06