Home > OS >  Saving SQLite query results as variables
Saving SQLite query results as variables

Time:12-30

So basically I'm looking to try to make a basic login for a WPF app and store certain user data into variables with C#. Problem I'm running into is separating the result of different datatypes into variables to use later in the app. Something similar to the GET command in PHP. I have seen some documentation about creating a separate class replicating the data you need and could probably run individual queries for each variable, but that just feels wrong and I know there's a better way.

Here is my code so far:

Database databaseObject = new Database();
var userid = LoginTextBox.Text;
string query = "SELECT * FROM users WHERE userid = @userid";
SQLiteCommand myCommand = new SQLiteCommand(query, databaseObject.myConnection);
databaseObject.OpenConnection();
myCommand.Parameters.AddWithValue("@userid", userid);
SQLiteDataReader result = myCommand.ExecuteReader();
if (result.HasRows)
{
/* GET RESULT INTO VARIABLES */
}
else
{
LoginTextBox.Text = "";
}
databaseObject.CloseConection();

Don't think I'm too off here just need a push in the right direction :)

CodePudding user response:

You can create a User class that has all the properties coming back from the table.

Something like:

public class User {
    public int UserId { get; set }
    public string UserName { get; set; }
}

And then just read the properties from your SQLiteDataReader and assign them to the properties of the class:

var user = new User();
user.UserId = (int)result["userid"];
user.UserName = (string)result["username"];
  • Related