简体   繁体   中英

SqlCommand AddWithValue

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?

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM