NewPassionnate NewPassionnate - 8 days ago 7
SQL Question

store value from sql statement in variable

My user logs in with username and password, I check in the database if he exists.

I would like after the connection, to get the UserID from the connected user and put it in a variable that I will be able to user later on in my program.


My table user and my two functions. i didn't add all the code as I don't think it is necessary.


+-----------------------------------------+
| User |
+------------+------------+---------------+
| UserID | Username | password |
| 1 | abc | def |
| 2 | ghi | jkl |
+------------+------------+---------------+


public int Login(string Username, string Password)
{
try
{
clsDataSource.mycon = new OleDbConnection(@"Provider=...");
OleDbCommand cmd = new OleDbCommand("Select * from Users where email=@email and pwd=@pwd", clsDataSource.mycon);
cmd.Parameters.AddWithValue("@email",Username);
cmd.Parameters.AddWithValue("@pwd",Password);
clsDataSource.mycon.Open();
dr = cmd.ExecuteReader();
DataTable dt = new DataTable();
dt.Load(dr);

clsDataSource.mycon.Close();

//code to login

return 0;
}
catch (Exception ex)
{
throw ex;
}
}


private void button1_Click(object sender, EventArgs e)
{
//code to check the login

}

Answer

Check this:

var ID = (int)cmd.ExecuteScalar();

this should help!