Search code examples
c#oledb

Syntax error in UPDATE for C# using Oledb


I am creating a simple app where users create accounts. I want for the user to be able to change their password after making the account.

I am making this in C# using Oledb.

 string test = "testing";
 con.Open();
 OleDbCommand command = new OleDbCommand();
 command.Connection = con;
 string query = "UPDATE tbl_users SET password = '" + test + "' WHERE username = '" + txtLoginUsername.Text + "'";
 MessageBox.Show(query);
 command.CommandText = query;

 command.ExecuteNonQuery();
 con.Close();

I keep getting the error: " System.Data.OleDbException: 'Syntax error in UPDATE'"

This error is occuring in the line:

command.ExecuteNonQuery();

Solution

  • Use this syntax

    Use bracket for password in query because password is reserved word

    link List of reserved world

            using (var connection = new OleDbConnection("Your Connection String"))
            {
                var query = "UPDATE tbl_users SET [password] = @password WHERE username = @username";
    
                using (var command = new OleDbCommand(query, connection))
                {
                    
                        connection.Open();
                     
                        command.Parameters.AddWithValue("@password", "test");
                        command.Parameters.AddWithValue("@username", txtLoginUsername.Text);
    
                        command.ExecuteNonQuery();
                   
                }
            }