首页 > 解决方案 > 单击提交按钮时出现语法错误,我的 SQL 表有问题,所以想知道它是否可以链接

问题描述

当我在注册表单上单击提交时出现此错误 -

System.Data.SqlClient.SqlException:'关键字'表'附近的语法不正确。'

下面是我的代码:

if(IsPostBack)
{
    SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString);
    conn.Open();
    string checkuser = "select count(*) from Table where UserName='" + TextBoxUN.Text +"'";
    SqlCommand com = new SqlCommand(checkuser, conn);
    int count = Convert.ToInt32(com.ExecuteScalar());
    {
        Response.Write("User already Exists");
    }


    conn.Close();

标签: c#web

解决方案


As pointed out in the comments by MickyD and Dour High Arch, "Table" is a reserved word in SQL.

You can avoid the error by putting Table inside of square brackets ([ ]) in the query:

string checkuser = "select count(*) from [Table] where UserName='" + TextBoxUN.Text +"'";

However, this isn't addressing the real problem - design. You have a table named Table. You should strongly consider giving it a real name based on what it will be used for (e.g., "Students", "Sales", etc.).

Security

Also, you have a SQL injection vulnerability. You should look up what this means and how to parameterize a query.


推荐阅读