Reputation: 149
I've been trying to insert a specific data to my database (in my case it is Microsoft Access), this is the following code I wrote using c#:
string sql = "Insert into Orders(User,PID,PName,Price,Amount)" +
" values('" + od.User + "','" + od.Pid + "','" +
od.Pname + "','" + od.Price + "','" + od.Amount + "')";
now I assume the form I wrote is perfectly fine , isnt it? the error I get is:
Syntax error in INSERT INTO statement.
Upvotes: 0
Views: 167
Reputation: 18843
Here is an example that you can follow I have pasted a copy from something I just wrote
you may want to follow this for future references pay attention to how the Parameters.AddWithValue()
method is being used instead of building the string query string with Quoted
values
private void btnInsert_Click(object sender, EventArgs e)
{
using(SqlConnection con = new SqlConnection(connString))
{
con.Open();
string Sql = "INSERT INTO Uyeleri (dID, FullName, Address, Mobile, Email, Comments ) " +
"VALUES (@id, @name, @address, @mobile, @email, @comments");
using(SqlCommand cmd = new SqlCommand(Sql, con))
{
cmd.Parameters.AddWithValue("@id", txtdID.Text);
cmd.Parameters.AddWithValue("@name", txtAdiSoyadi.Text);
cmd.Parameters.AddWithValue("@address", txtAddress.Text);
cmd.Parameters.AddWithValue("@mobile", txtMobile.Text);
cmd.Parameters.AddWithValue("@email", txtEmail.Text);
cmd.Parameters.AddWithValue("@comments", txtComments.Text);
cmd.ExecuteNonQuery();
}
}
Upvotes: 1
Reputation: 7737
Change your code so you use a parameterized command:
string sql = "Insert into Orders([User],PID,PName,Price,Amount) values(@user, @pid, @pname, @price, @amount)";
..here you will need to add your parameters to your command
This both avoids SQL injection attacks and prevents errors with unescaped characters.
Upvotes: 1
Reputation: 700192
User
is a reserved keyword. Put brackets around it to specify that you want to use it as an identifier, not a command:
string sql = "Insert into Orders([User],PID,PName,Price,Amount)" +
" values('" + od.User + "','" + od.Pid + "','" +
od.Pname + "','" + od.Price + "','" + od.Amount + "')";
This should solve your immediate problem. Using a parameterised query (as several has suggested) is good to avoid future problems also.
Upvotes: 3