Rhonwen Van Druten
Rhonwen Van Druten

Reputation: 45

SQL selecting multiple columns at once

Hallo I am still new in this game. I am struggling to select the username and password from the database to verify it.

What this below mentioned code can do is ONLY select the username.

I need help to modify the select statement to select both username and password.

 public override int SelectUser(string username, ref User user)
 {
  int rc = 0;

    try
    {
        _sqlCon = new SQLiteConnection(_conStr);
        bool bRead = false;
        user = new User();

        _sqlCon.Open();

// This selection string is where I am struggling.

      string selectQuery = "SELECT * FROM Users WHERE [uUsername] = ' " + username + " ' ";

        SQLiteCommand sqlCmd = new SQLiteCommand(selectQuery, _sqlCon);
        SQLiteDataReader dataReader = sqlCmd.ExecuteReader();
        bRead = dataReader.Read();
        if(bRead == true)
        {
            user.Username = Convert.ToString(dataReader["uUsername"]);
            user.Password = Convert.ToString(dataReader["uPW"]);
            rc = 0;
        }// end if
        else
        {
            rc = -1;
        }// end else
        dataReader.Close();
    }// end try
    catch(Exception ex)
    {
        throw ex;
    }// end catch
    finally
    {
        _sqlCon.Close();
    }// end finally
    return rc;
}// end method

Upvotes: 0

Views: 3788

Answers (1)

Steve
Steve

Reputation: 216293

You add the AND logical operator to the WHERE first condition to get a double condition. However, this whole approach using string concatenations is wrong.
It is a well known source of bugs and a big security risk called Sql Injection

Instead you use a parameterized query like this

string selectQuery = @"SELECT * FROM Users 
                       WHERE [uUsername] = @name AND 
                             [uPw] = @pass";

SQLiteCommand sqlCmd = new SQLiteCommand(selectQuery, _sqlCon);
sqlCmd.Parameters.Add("@name", DBType.String).Value = username;
sqlCmd.Parameters.Add("@pass", DBType.String).Value = password;
SQLiteDataReader dataReader = sqlCmd.ExecuteReader();
bRead = dataReader.Read();
....

I assume that you have in the variable password the value to search for, change it to your actual situation.

Consider also that storing passwords in clear text inside a database is another security risk to avoid. The question Best way to store password in a database explains in great detail the reasons and the correct way to do it

Upvotes: 2

Related Questions