1

I am writing the following code in my C-Sharp Form Application and its giving me the following error.

> Syntax error in INSERT INTO statement.


OleDbCommand cmd =
    new OleDbCommand(
            "Insert into Info (username, password) Values ('"
          + username
          + "', '" 
          + password 
          + "')"
        , conn
    );
collapsar
  • 17,010
  • 4
  • 35
  • 61
Taha Kirmani
  • 101
  • 1
  • 1
  • 9

3 Answers3

3

The word PASSWORD is a reserved keyword. To use it you should enclose the string in square brackets

OleDbCommand cmd = new OleDbCommand("Insert into Info (username, [password]) Values ('" + username + "', '" + password + "')", conn);

And please, please, do not use string concatenation to build sql statements. It is a very bad practice that leads to other syntax errors (username or password with single quotes) or worst to a sql injection Attacks. Take a look here to what could happen if you have a smart and malicious user

OleDbCommand cmd = new OleDbCommand("Insert into Info (username, [password]) Values (?,?)", conn);
cmd.Parameters.AddWithValue("@p1", username);
cmd.Parameters.AddWithValue("@p2", password);
cmd.ExecuteNonQuery();
Community
  • 1
  • 1
Steve
  • 213,761
  • 22
  • 232
  • 286
  • Can i also write Select command like this, oledbCommand cmd= new oledbcommand ("Select * from Table where id= ? and password= ?") – Taha Kirmani Apr 26 '13 at 16:11
  • Yes of course, the concept is the same. The parameters should always used to pass user input text. You can't use a parameter to express the table's name or column's name though. – Steve Apr 26 '13 at 17:07
2

You need to bracket off password. It's a reserved word.

OleDbCommand cmd = 
    new OleDbCommand("Insert into Info (username, [password]) Values ('" + username + "', '" + password + "')", conn);
David Hoerster
  • 28,421
  • 8
  • 67
  • 102
1

Maybe there's an illegal character (such as a single quote) within the username or password variables. Make sure they're sanitized.

Hebron George
  • 329
  • 1
  • 6
  • 21
  • That's a good point, but the better way to deal with that possibility is to use a parameter query as Steve suggested. – HansUp Apr 26 '13 at 15:36