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
    );

3 Answers 3

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();
Sign up to request clarification or add additional context in comments.

2 Comments

Can i also write Select command like this, oledbCommand cmd= new oledbcommand ("Select * from Table where id= ? and password= ?")
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.
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);

3 Comments

@HansUp - thought it was username, but user is the reserved word. Typed too quickly. :)
Yeah, username looks suspicious. :-) And the brackets wouldn't hurt ... so including them wasn't a problem. You earned +1 based on [password].
@HansUp thanks! Yes, the square brackets don't hurt (at least, I don't think they do).
1

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

1 Comment

That's a good point, but the better way to deal with that possibility is to use a parameter query as Steve suggested.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.