Reputation: 375
I'm developing a classic WEBForms application in C# and when I have to authenticate the user, I read from SQL database the user data using a query like that:
SELECT userid,username,email,city FROM USERS where username='blablabla' and password='blablabla'
I want to use this sql query in my method that returns a DTO
Object that I defined in my UserValue
class.
I'm thinking to use a dataset
to fill user data executing the query.
Is it the correct approach or is it too expensive and useless to use dataset
to read one row from a query?
Can you advice me?
thanks
Upvotes: 3
Views: 7869
Reputation: 2080
For getting only one record from database or one by one record from database,"Data Reader" is Good Approach.Check the sites below You can get clear Idea on Data Reader.
http://www.aspdotnet-suresh.com/2012/10/aspnet-difference-between-datareader.html http://msdn.microsoft.com/en-us/library/haa3afyz.aspx http://www.akadia.com/services/dotnet_data_reader.html
Upvotes: 4
Reputation: 28520
Here's a code snippet (this is for MS SQL, but other flavors of SQL should be similar) to illustrate what I'm talking about in my comment:
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand("SELECT userid,username,email,city FROM USERS where username=@username and password=@password", con);
cmd.Paramters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", password);
cmd.CommandType = CommandType.Text;
UserInfo info = new UserInfo();
using (SqlDataReader rdr = cmd.ExecuteReader())
{
if (rdr.HasRows)
{
rdr.Read(); // get the first row
info.UserID = rdr.GetInt32(0);
info.UserName = rdr.GetString(1);
info.Email = rdr.GetString(2);
info.City = rdr.GetString(3);
}
}
}
This example also shows how to do parameterized queries, which are essential for preventing SQL Injection attacks.
Also, rather than looping through the reader, I check to see if it has rows and if it does I read the first row only (and since you're dealing with user information there should theoretically be only one row) and populate the DTO.
Hopefully this will illustrate my comment to your question.
Upvotes: 3