'Incorrect error near ',' (inserting values into a table)
I'm trying to add information to a table when it is input, but get an error saying there is incorrect syntax, and I have no clue where I've gone wrong.. I'm using C# and SQL Server.
Here is my code:
Con.Open();
string query = "insert into tablepassengers values(" + tbpassno.Text + "','" + tbname.Text + "','" + tbaddress.Text + "','" + tbnumber.Text + "','" + cbnationality.SelectedItem.ToString() + "')'";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.ExecuteNonQuery();
MessageBox.Show("recorded");
Con.Close();
Solution 1:[1]
Change the query to:
string query = "insert into tablepassengers values('" + tbpassno.Text + "','" + tbname.Text + "','" + tbaddress.Text + "','" + tbnumber.Text + "','" + cbnationality.SelectedItem.ToString() + "')";
Basically, you forgot a ' after opening the parenthesis and you added an extra ' after closing it.
Though, to be honest, it'd be better to use parameters for security purposes.
For example,
string query = "insert into tablepassengers values(@1, @2, @3, @4, @5)";
SqlCommand cmd = new SqlCommand(query, Con);
cmd.Parameters.AddWithValue("@1", tbpassno.Text);
cmd.Parameters.AddWithValue("@2", tbname.Text);
cmd.Parameters.AddWithValue("@3", tbaddress.Text);
cmd.Parameters.AddWithValue("@4", tbnumber.Text);
cmd.Parameters.AddWithValue("@5", cbnationality.SelectedItem.ToString());
cmd.ExecuteNonQuery();
For more, read SQLCommand.Parameters.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
