-1

I get this error when I click Submit on my registration form -

System.Data.SqlClient.SqlException: 'Incorrect syntax near the keyword 'Table'.'

Below is my code:

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();
elmer007
  • 1,412
  • 14
  • 27
  • 4
    Maybe enclose `Table` with `[]`. Like so: `[Table]`. Probably not the best name for a table BTW –  Dec 05 '19 at 23:09
  • 3
    And what about if count is zero? – Steve Dec 05 '19 at 23:11
  • 3
    You need to [use parameters](https://stackoverflow.com/questions/2675610/) before someone creates a user name like `Bobby'AND'0'='`. And `Table` is an SQL reserved word, you should create meaningful table names. – Dour High Arch Dec 05 '19 at 23:11
  • 1
    Ah yes, adding to Steve's fine comment - did you forget an `if` statement? –  Dec 05 '19 at 23:11

1 Answers1

0

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.

elmer007
  • 1,412
  • 14
  • 27