c# - Get & Set MySQL Select -
what missing here, seems main form not calling method tsdbcon class , not connecting database, need help, i'm new get:set properties, doing wrong or what? thanks.
public class tsdbcon { private string _user; private string _pass; public string user { { return _user; } set { _user = value; } } public string pass { { return _pass; } set { _pass = value; } } public void queryuser() { tsdbcon = new tsdbcon(); var connsettings = configurationmanager.connectionstrings["mydb"]; { string cn = connsettings.connectionstring; mysqlconnection conn = new mysqlconnection(cn); mysqlcommand cmd = new mysqlcommand("select * users user = @user , pass = @pass", conn); cmd.parameters.addwithvalue("@user", get.user); cmd.parameters.addwithvalue("@pass", get.pass); mysqldatareader reader = cmd.executereader(); conn.open(); while (reader.read()) { get.user = reader["user"].tostring(); get.pass = reader["pass"].tostring(); } } } } code in main form tsdbcon ts = new tsdbcon(); private void getuser() { ts.user = txtuser.text; ts.pass = txtpass.text; }
what missing here, seems main form not calling method
tsdbcon
class , not connecting database, need help, i'm new get:set properties, doing wrong or what?
yes, doing few things wrong.
i want validate if user entered correct user , pass through textboxes.
your code contains several problems:
- when create
idisposable
instances (e.g.mysqlconnection
) need dispose them. easiest way ensure wrap them inusing
block. - if create local temporary instance of object (e.g.
tsdbcon = new tsdbcon();
) value assign properties gone after leave scope of method in. unless return function result or throughref
orout
parameter.
to check if user name / password combination correct, code sample provided, might want change things bit this:
public class tsdbcon { private const string existsquery = "select count(*) users user = @user , pass = @pass"; public tsdbcon(string user, string pass) { user = user; pass = pass; } public string user { get; set; } public string pass { get; set; } public bool loginexists() { var connsettings = configurationmanager.connectionstrings["mydb"]; var cn = connsettings.connectionstring; using (var conn = new mysqlconnection(cn)) { conn.open(); using (cmd = new mysqlcommand(existsquery, conn)) { cmd.parameters.addwithvalue("@user", user); cmd.parameters.addwithvalue("@pass", pass); var count = (int)cmd.executescalar(); return count > 0; } } } }
and in main form use this:
ts = new tsdbcon(txtuser.text, txtpass.text); userloginexists = ts.loginexists();
one last remark: never store password unencrypted.
Comments
Post a Comment