Search code examples
c#oledb

C# - oledb exception syntax error (0x80040E14) in insert into statement


Hi I've got a problem: My OleDbCommand not working.

Element of code:

    private void Btn_Click(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = connection;
            cmd.CommandText = "insert into Account (Nick,Password) values ('" + NickEnter.Text + "', '" + PassEnter.Text + "');";

            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error! | " + ex, "Error!");
        }
    }

Solution

    • You are using reserved words for column names. You need to escape these using square brackets.
    • Also you should use parameters for your values. This guards against sql injection (where possible) and also ensures that a value with a single quote does not destroy the statement.
    • Finally I noticed you have a field named password and a plain text value, you should never store passwords as plain text. Instead store a 1 way hash of the password. There are many libraries out there you can use.
    private void Btn_Click(object sender, EventArgs e)
    {
        try
        {
            connection.Open();
            OleDbCommand cmd = new OleDbCommand();
            cmd.Connection = connection;
            cmd.CommandText = "INSERT INTO [Account] ([Nick],[Password]) values (?,?);";
    
            // note that order is critical here
            command.Parameters.Add(new OleDbParameter("@nick", OleDbType.VarChar)).Value = NickEnter.Text;
            command.Parameters.Add(new OleDbParameter("@password", OleDbType.VarChar)).Value = PassEnter.Text;
    
            cmd.ExecuteNonQuery();
        }
        catch (Exception ex)
        {
            MessageBox.Show("Error! | " + ex, "Error!");
        }
    }