c# - System.Data.SqlClient.SqlException : 'Incorrect syntax near ' `'.'

标签 c# sql-server asp.net-mvc visual-studio

我正在尝试使用 ASP.NET 创建一个登录字段,该字段将从文本框字段中获取输入,并根据我的数据库中的“用户”表检查它们。这些列是 User IDPassword。但是一个错误

System.Data.SqlClient.SqlException: 'Incorrect syntax near '`'

在使用登录表单时出现。我看不出语法有任何问题...

我是新手,如果错误很明显,请原谅!

public partial class Login_Page : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        lblErrorMessage.Visible = false;
        SqlConnection con = new SqlConnection("Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True");
        con.Open();
    }

    protected void btnLogin_Click(object sender, EventArgs e)
    { 
            SqlConnection con = new SqlConnection();
            con.ConnectionString = "Data Source=JACKS-PC\\SQLEXPRESS;Initial Catalog=CBR;Integrated Security=True";
            con.Open();

            string userid = txtUsername.Text.Trim();
            string password = txtPassword.Text.Trim();

            SqlCommand cmd = new SqlCommand("select `user id`,`password` from user where `user id`='" + txtUsername.Text + "'and `password`='" + txtPassword.Text + "'", con);

            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();

            da.Fill(dt);

            if (dt.Rows.Count > 0)
            {
                Session["username"] = txtUsername.Text.Trim();
                Response.Redirect("Homepage.aspx");
            }
            else
            {
                lblErrorMessage.Visible = true;
            }

            con.Close();
    }
}

最佳答案

  1. 只需删除“`”字符即可。

  2. 您的代码容易受到注入(inject)尝试使用 SqlCommand.Parameters.Add() 方法添加值。

使用此代码:

SqlCommand cmd = new SqlCommand("select userid, password from user where user id = @id and password = @password", con);

cmd.Parameters.Add("@id", SqlDbType.VarChar).Value = txtUsername.Text;
cmd.Parameters.Add("@password", SqlDbType.VarChar).Value = txtPassword.Text;

正如@marc_s 提到的,user id 不是一个有效的列名,它应该像 userid 或者如果它有空格,它应该像:[用户名]

关于c# - System.Data.SqlClient.SqlException : 'Incorrect syntax near ' `'.' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54843315/

相关文章:

c# - 如何在 C# 中生成 8 位唯一和随机数

c# - 使用 LINQ 筛选嵌套集合并返回主对象

c# - 调用SQL Server存储过程的问题

sql - 计算 SQL Server 查询中的唯一行

c# - 将 HttpContext.Current.User 与异步等待一起使用的正确方法

c# - RadioButtonFor 和标签

c# - 根据数据库值选择 RadioButton

c# - 如何获取和更改未命名控件的属性?

c# - 如何在 Asp.net Core 运行时从 DependencyInjection 解析泛型类型服务

mysql - #1146 - 表 'phpmyadmin.pma_column_info' 不存在