-1

I'm creating an application where I store my inputs (name, age, phone) from the textbox and when I click Submit, it should store whatever I input onto the textbox into the database but I keep getting this error.

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code. Additional Information: Incorrect syntax near the keyword 'Table'.

Here is the following code:

protected void Button1_Click(object sender, EventArgs e)
    {
        String p = UniqueNumber();
        SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings
            ["ConnectionString"].ConnectionString);
        con.Open();
        String str = "insert into Table(uniqueno, name, age, number) values( '" 
            + Label1.Text + "','" + txtName.Text + "','" + txtAge.Text + "','" + txtNumber.Text + "')";
        SqlCommand cmd = new SqlCommand(str, con);
        cmd.ExecuteNonQuery();
        con.Close();
        Session["id"] = Label1.Text;
        Session["name"] = txtName.Text;
        try
        {
            Response.Redirect("unique.aspx");
        }
        catch
        {
            Label1.Text = "Please enter correct details....";
            this.Label1.ForeColor = Color.Red;
        }
    }
Daniel
  • 10,641
  • 12
  • 47
  • 85
amiiBRO
  • 1
  • 2
  • 2
    sql injection vulnerability. use parameterized queries – Seth Flowers Aug 31 '16 at 18:01
  • Do you really mean the error happens only when trying to debug the application, rather than when running it? If it happens on any run, change your question to "when trying to insert into a table" – Gonen I Aug 31 '16 at 18:04
  • also change this line `Response.Redirect("unique.aspx");` to `Response.Redirect("~unique.aspx");` also I hope you are familiar with PostBacks and how they work.. make sure when debugging that the values you are passing to SQL Insert command are not null or empty and read up on `Parameterized Query's` and how to use them and if `Table` is the name wrap it around brackets like this `[Table]` since Table is a Reserved Word in SQL – MethodMan Aug 31 '16 at 18:08
  • As others have mentioned, you shouldn't name your table as 'Table' and you should not create the statement with string concatenation (it is vulnerable to SQL injection attack). I see that you are passing all of the values as string types. If their actual type is different (for example if you have defined the type of column 'age' as 'int'), then you are getting the error because of the single quotes that you are putting next to the values. – Sparrow Aug 31 '16 at 18:10

1 Answers1

0

"Table" is keyword, although you may have stored data into the Table, I don't think SQL server would allow you to query that.

Surprisingly, it allows us to have a table named Table but when we try to select, it throws an error. And as @seth flower mentioned, try avoiding SQL injection vulnerabilities.

enter image description here

atp9
  • 890
  • 1
  • 11
  • 23