Well I am working on a simple login screen for a game and it uses username and password authentication. It connects to the database checks to see if username and password are there and then sees if it matches the data. If you insert the right username and password it works fine, but if you do one that is not in the database it fails and crashes. I was wondering am I doing this right? code below.
private void loginButton_Click(object sender, EventArgs e)
{
string connectionString = "datasource=STUFFZ;database=users";
string select = "SELECT Username, Password FROM RegularUsers WHERE Username = '" + usernameBox.Text + "' AND Password = '" + passwordBox.Text + "'";
MySqlConnection my = new MySqlConnection(connectionString);
MySqlCommand command = new MySqlCommand(select, my);
my.Open();
//String strResult = String.Empty;
//strResult = (String)command.ExecuteScalar();
string[] bba = new string[2];
bba[1] = (String)command.ExecuteScalar();
my.Close();
if (bba[1].Equals(usernameBox.Text))
{
AdminPanel bb = new AdminPanel();
bb.Show();
}
else
{
MessageBox.Show("INCORRECT USER/PASS!");
}
}
The incorrect USER/PASS box never shows if you insert it wrong.
Couple of comments:
SqlConnectionandSqlCommandintousing(....) { ... }blocks.ExecuteScalar()– that call only works for single row, single column returnsSo all in all, your code should be something like this:
Furthermore, I think this code is a tad messy since you’re doing data access (selecting from SQL Server) and UI access (reading out textboxes, popping up dialog boxes) in the same snippet of code-
You should strive for more separation of concerns, e.g.
CheckUserNamethat takes in a user name and password as string, and returns e.g. aboolBut mixing UI, logic and data access code – it gets messy and a maintenance nightmare really quickly!