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

1

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!");
        }
    }
c#
oledb
asked on Stack Overflow Apr 17, 2018 by Macol • edited Apr 17, 2018 by Pogrindis

1 Answer

1
  • 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!");
    }
}
answered on Stack Overflow Apr 17, 2018 by Igor • edited Apr 17, 2018 by Igor

User contributions licensed under CC BY-SA 3.0