Search code examples
c#databasems-accessoledb

Fail to update Access Database through OleDbAdapter


So I have an Input form where I input values for each column. Then after declaring the connection, adapter, command and query the following code is executed with no exception thrown but also without updating the database:

    private void BtnOk_Click(object sender, EventArgs e)
    {
        OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=[MyDirectory]\Database.accdb");    
        conn.Open();
        string query = "UPDATE [Users] SET [User]=" + txtUser.Text 
        + ", [Password]=" + txtPass.Text 
        + ", [IsAdmin]=" + chBAdmin.Checked.ToString() 
        + " WHERE ID=" + txtID.Text + "";
        OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
        OleDbCommand comm = new OleDbCommand
        {
            CommandType = CommandType.Text,
            CommandText = query,
            Connection = conn
        };

        try
        {
            comm.ExecuteNonQuery();
            MessageBox.Show(query);
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
        conn.Close();
    }

Solution

  • You need to delimit the values with a single quote, e.g.

    string query = "UPDATE [Users] SET [User]='" + txtUser.Text + "'"
    

    However, you will probably get comments about SQL injection and should really use a parameterised query, rather than constructing a SQL string including user input.