sql - ADO.NET retrieve a user from the database with a query -
i have used linq info sql. it's fast , easy utilize i've heard requires more resource server compared normal queries.
so.. i'm trying improve queries now..
what want retrieve user database, query.
is possible this:
user model:
[key] public int userid { get; set; } public string username { get; set; } public string password { get; set; } public string passwordsalt { get; set; } public string money { get; set; }
query:
public user getuser(string username) { string sql = "select * users username = @username"; user user = null; using (sqlconnection connection = new sqlconnection(configurationmanager.connectionstrings["connectionstring"].connectionstring)) { seek { sqlcommand cmd = new sqlcommand(sql, connection); cmd.parameters.add("@username", sqldbtype.varchar, 12).value = username; connection.open(); user = (user)cmd.executereader(); } grab { } } homecoming user; }
or forced utilize datareader , insert every cell new user model, , homecoming it?
//newbie
update 1:
how proceed if want result genericcollection of user model?
a sqldatareader
handle results, kind of cursor. need step through , pick out values, indexed result's column names. seek this:
public user getuser(string username) { string sql = "select * users username = @username"; user user = null; using (sqlconnection connection = new sqlconnection(configurationmanager.connectionstrings["connectionstring"].connectionstring)) { seek { sqlcommand cmd = new sqlcommand(sql, connection); cmd.parameters.add("@username", sqldbtype.varchar, 12).value = username; connection.open(); sqldatareader dr = cmd.executereader(); if (dr.read()) { // you're pointed @ first result row user = new user { userid = dr["userid"], name = dr["name"], whatever = dr["whatever"] }; } } grab { } } homecoming user; }
also, ado.net recommends using parameters.addwithvalue
method. find lot easier because don't have deal types , lengths , forth, , i've never had problems results. so, instead of this:
cmd.parameters.add("@username", sqldbtype.varchar, 12).value = username;
you can utilize this:
cmd.parameters.addwithvalue("@username", username);
sql sql-server asp.net-mvc ado.net
No comments:
Post a Comment