0

I have already build a successful login form. But I want to have the opportunity to create a new account. I have two textboxes; one for username and one for password. Once the button is clicked, it needs to write this data to a MS Access 2002-2003 database file. But when I click the button I get the following error message:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: Syntax error in INSERT INTO statement.

This is the code I am using:

    private void buttonRegistreren_Click(object sender, EventArgs e)
    {
        connection.Open();
        OleDbCommand command = new OleDbCommand();
        command.Connection = connection;
        command.CommandText = "INSERT INTO Gebruikers (Username, Password) values('" + textBoxUserregist.Text + "', '" + textBoxPassregist.Text + "')";
        command.ExecuteNonQuery();
        connection.Close();
    }

Somebody knows what I am doing wrong?

Cœur
  • 37,241
  • 25
  • 195
  • 267
Needsomehelp
  • 77
  • 1
  • 10

1 Answers1

0

Password is a reserved keyword in MS-Access, you need to encapsulate it between square brackets

command.CommandText = "INSERT INTO Gebruikers (Username, [Password]) ...."

said that please remember that string concatenations to build sql command is a very bad practice and leads to numerous problems. Start using parameters as soon as possible as in the example below

private void buttonRegistreren_Click(object sender, EventArgs e)
{
    using(OleDbConnection cn = new OleDbConnection(.....))
    using(OleDbCommand command = new OleDbCommand(@"INSERT INTO Gebruikers
                    (Username, [Password]) values(@name, @pwd)", cn))
    {
        cn.Open();
        command.Parameters.Add("@name", OleDbType.NVarWChar).Value =textBoxUserregist.Text ;
        command.Parameters.Add("@pwd", OleDbType.NVarWChar).Value = textBoxPassregist.Text;
        command.ExecuteNonQuery();
    }
}
Steve
  • 213,761
  • 22
  • 232
  • 286