1
SqlCommand command = new SqlCommand("SELECT * FROM users WHERE Username =  ? AND Password = ?", connection);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
SqlDataReader reader = null;
reader = command.ExecuteReader();

When I run the program I get

Incorrect syntax near '?'.

On this line:

reader = command.ExecuteReader();

Can anyone see what I´m doing wrong?

1
  • 1
    is the query being run on SQL Server.. and if so what version..? is this just a standard Query or is this run against a StoredProcedure.. if it's a stored procedure.. change the "Username" to be "@Username" and "Password" to be "@Password" Commented Jan 17, 2012 at 14:13

3 Answers 3

9
using(SqlCommand command = new SqlCommand("SELECT * FROM users WHERE Username =  @Username AND Password = @Password", connection))
{
  command.Parameters.AddWithValue("@Username", username);
  command.Parameters.AddWithValue("@Password", password);
  using(SqlDataReader reader = command.ExecuteReader())
  {
    while(reader.Read())
    {
      //do actual works
    }
  }
}

Improved with using keywords, which is not necessary, but recommended

Sign up to request clarification or add additional context in comments.

2 Comments

Well worth adding... if ((reader.HasRows) && (reader.Read())) { }
@Lloyd: Its not necessary. If reader.HasRows() returns false, so will reader.Read().
1
SqlCommand command = new SqlCommand(
    "SELECT * FROM users WHERE Username = @Username AND Password = @Password",
    connection);
command.Parameters.AddWithValue("Username", username);
command.Parameters.AddWithValue("Password", password);
SqlDataReader reader = null;
reader = command.ExecuteReader();

You might want to read up on sql.

2 Comments

So... the @ sign is optional in the AddWithValue?
@JohnHenckel Yep. Works with or without.
1

Which DBMS are you using? If you're using SQL Server, that is incorrect syntax for the query. You need:

SqlCommand cmd = 
    new SqlCommand(@"select * 
                     from users 
                     where username = @username and password = @password");

command.Parameters.AddWithValue("@username", username);
command.Parameters.AddWithValue("@password", password);

Comments

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.