ASP.NET C# - using dataset to read one row? -
i'm developing classic webforms application in c# , when have authenticate user, read sql database user data using query that:
select userid,username,email,city users username='blablabla' , password='blablabla'
i want use sql query in method returns dto
object defined in uservalue
class. i'm thinking use dataset
fill user data executing query.
correct approach or expensive , useless use dataset
read 1 row query?
can advice me?
thanks
here's code snippet (this ms sql, other flavors of sql should similar) illustrate i'm talking in comment:
using (sqlconnection con = new sqlconnection(connectionstring)) { con.open(); sqlcommand cmd = new sqlcommand("select userid,username,email,city users username=@username , 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(); // first row info.userid = rdr.getint32(0); info.username = rdr.getstring(1); info.email = rdr.getstring(2); info.city = rdr.getstring(3); } } }
this example shows how parameterized queries, essential preventing sql injection attacks.
also, rather looping through reader, check see if has rows , if read first row (and since you're dealing user information there should theoretically 1 row) , populate dto.
hopefully illustrate comment question.
Comments
Post a Comment