I'm writing an application which stores user information. Currently the user is supposed to update their Name, Height, Weight and Birthday.
string height = TB_ClientHeight.Text;
string weight = TB_ClientWeight.Text;
string name = TB_ClientName.Text;
string bday = dateTimePicker1.Value.ToString("dd-MM-yyyy");
int heightint = Convert.ToInt32(height);
int weightint = Convert.ToInt32(weight);
It's updated by calling the public static string
username variable from another form and using that as the WHERE UserName = @username
.
usernamestringo = Login.usernameFromLogin;
I've followed other SO answers in this context and corrected some issues (like preventing SQL Injection). However I'm still getting a syntax error while updating these fields as claimed by OleDbException
.
using (OleDbConnection myCon = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=O:\Repos\Database\Database.accdb;Persist Security Info=False"))
using (OleDbCommand cmd = new OleDbCommand())
{
cmd.CommandType = CommandType.Text;
string query = "UPDATE TPersons SET Name=@Name, SET Height=@Height, SET Weight=@Weight, SET Bday=@Bday " + " WHERE FirstName= @username";
cmd.CommandText = query;
cmd.Parameters.AddWithValue("@Name", name.ToString());
cmd.Parameters.AddWithValue("@Height", heightint.ToString());
cmd.Parameters.AddWithValue("@Weight", weightint.ToString());
cmd.Parameters.AddWithValue("@Bday", bday.ToString());
cmd.Parameters.AddWithValue("@username", usernamestringo);
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("Updated!", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
cmd.Parameters.Clear();
}
The OleDbException
is:
Index #0 NativeError: -526847407 Source: Microsoft Access Database Engine SQLState: 3000 Description (message): Syntax error in UPDATE statement.
Could anyone guide me where my syntax is wrong? Thank you!
The UPDATE syntax is
The SET keyword precedes only the first column to update, and you have another problem with the NAME column. In Access this is a reserved keyword. Use brackets around that column name (or better change it to something not so troublesome)
So:
Not strictly related to your current problem, but you should look also at this article Can we stop using AddWithValue already? The DbCommand.AddWithValue is a shortcut with numerous drawbacks. Better avoid it.