Select MySQL Data in C# - c#

I want to login to the program using c#, with my username and password that's stored to the SQL Database in phpmyadmin.
This is what I have so far.
private void button1_Click(object sender, EventArgs e)
{
MySqlConnection connection;
string server = "localhost";
string database = "login";
string uid = "root";
string password = "";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
try
{
connection.Open();
if (connection.State == ConnectionState.Open)
{
connection.Close();
Form1 frm = new Form1(this);
frm.Show();
Hide();
}
else
{
MessageBox.Show("Database Connection Failed", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
catch (Exception ex)
{
MessageBox.Show("An Error Occured, Try again later.", "Epic Fail", MessageBoxButtons.OKCancel, MessageBoxIcon.Asterisk);
}
}
It connects to the database, however I don't want it to show the form1 Until both a valid Username and Password have been entered.
I'm guessing I need to use SELECT * FROM but I'm not exactly sure how to go about it.

You can use this way to see if username and password match
MySqlCommand cmd = dbConn.CreateCommand();
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = #username and password=#password";
command.Parameters.Add("#username", txtUserName.Text);
command.Parameters.Add("#password", txtPassword.Text);
var count = cmd.ExecuteScalar();
if(count>0)
//Logged In
Just to say, if you use a query like
cmd.CommandText = "SELECT count(*) from tbUser WHERE UserName = '"+txtusernam +"'";
You will be open to SQL Injection
Warning
As Steve mentioned in comments Passwords in clear text are a vulnerability of the same magnitude of string concatenation

you make try this one
using(var con = new MysqlConnection{ ConnectionString = "your connection string " })
{
using(var command = new MysqlCommand{ Connection = con })
{
con.Open();
command.CommandText = #"SELECT level FROM userTable WHERE username=#username, password=#password";
command.AddWithValue("#username", txtusername.Text);
command.AddWithValue("#password", txtpassword.Text);
var strLevel = myCommand.ExecuteScalar();
if(strLevel == DBNULL.Value || strLevel == Null)
{
MessageBox.Show("Invalid username or password");
return;
}
else
{
MessageBox.Show("Successfully login");
hide(); // hide this form and show another form
}
}
}

use below Query
Select * from UsersTable Where Username='"+username+"' AND password='"+password+"'
Then you can make a if condition that if your query contain a result (rows) then users authenticated (exists in Table)
Note:Select query may fetch multiple users having same userName and
password, its upto you to keep usersname unique in table

Related

I am working on a New user registration form that only contains of 3 fields, Username, password and confirm password

I am working on a user registration form containing only 3 fields Username,password and confirm password. But when i insert data, if password is mismatching, the exception appears form mismatch but on clicking OK, the data is inserted into db.
what should i do that it only insert on matching password
private void btn_save_Click(object sender, EventArgs e)
{
try
{
conn.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
string query = "INSERT INTO Users (username,newpassword)values('" + txt_newusr.Text + "','" + txt_password.Text + "')";
if (txt_password.Text == "" || txt_cnfpw.Text == "")
{
MessageBox.Show("Please enter values");
return;
}
if (txt_password.Text != txt_cnfpw.Text)
{
MessageBox.Show("Password confirm password are not matching");
txt_cnfpw.Focus();
}
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Record Saved successfully");
conn.Close();
}
}
You should change it like that
if (txt_password.Text == txt_cnfpw.Text)
{
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Record Saved successfully");
}
You have to do lots of corrections to make this work properly, Corrections like the following:
Make use of parameterized queries instead for concatenated queries to avoid injection
Process insert only after client-side validations(empty check password match etc)
Make use of using for managing connections and commands
I have added an example below, please have a look
try
{
string query = "INSERT INTO Users (username,newpassword)values(#username,#newpassword)";
bool CanInsertNewUser = true;
if (txt_newusr.Text=="" || txt_password.Text == "" || txt_cnfpw.Text == "")
{
CanInsertNewUser = false;
MessageBox.Show("Please enter values");
}
if (txt_password.Text != txt_cnfpw.Text)
{
CanInsertNewUser = false;
MessageBox.Show("Password confirm password are not matching");
txt_cnfpw.Focus();
}
if (CanInsertNewUser)
{
using (OleDbConnection conn = new OleDbConnection("GiveYourConnectionStringHere"))
{
using (OleDbCommand command = new OleDbCommand())
{
conn.Open();
command.Connection = conn;
command.CommandText = query;
command.Parameters.Add("#username", OleDbType.VarChar).Value = txt_newusr.Text;
command.Parameters.Add("#newpassword", OleDbType.VarChar).Value = txt_password.Text;
command.ExecuteNonQuery();
}
}
MessageBox.Show("Success");
}
}
catch (Exception ex)
{
MessageBox.Show("OLEDB issues : " + ex.Message.ToString());
}
In both the success and failure cases you are attempting to commit the transaction.
Save statements should only be executed if the password is matching. Move the save statements inside the success block as follows.
if (txt_password.Text == txt_cnfpw.Text)
{
MessageBox.Show(query);
command.CommandText = query;
command.ExecuteNonQuery();
MessageBox.Show("Record Saved successfully");
}
else
{
MessageBox.Show("Password confirm password are not matching");
txt_cnfpw.Focus();
}

While loop is not functioning correctly

I have a login program that have a user name texbox and password textbox. The program should get the user's name and password from the user and matching it with the name and password that is available in the access database file. The file is in bin/debug folder. The problem is the while loop is not working and I am getting only "Incorrect username and password message" from the loop. Can anyone help me please?
Here is my code:
private void loginButton_Click(object sender, EventArgs e)
{
try
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "select * from login where UserName= '" + userTextBox.Text + "'and Password= '" + passwordTextBOx.Text + "'";
OleDbDataReader reader = command.ExecuteReader();
int count = 0;
while (reader.Read())
{
count = count + 1;
}
if (count == 1)
{
this.Hide();
Form newForm = new Form();// create new form
newForm.Show();//display newform
}
if (count > 1)
{
MessageBox.Show("Duplicate UserName and Password");
}
else
{
MessageBox.Show("Incorrect UserName and Password");
}
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
If all you want is the number of rows returned, you should use SELECT COUNT(*) and ExecuteScalar:
command.CommandText = "select Count(*) from login where UserName= #Username and Password= #Password";
command.Parameters.AddWithValue("#Username", userTextBox.Text);
command.Parameters.AddWithValue("#Password", passwordTextBOx.Text);
OleDbDataReader reader = command.ExecuteScalar();
while (reader.Read())
{
count = reader.GetInt32(0);
}
Please note, that OleDb does not support named parameters. So while I named them #Username / #Password, these are in fact just placeholders. OleDb only uses positional parameters, so the order in which you add them to your query is important. Adding the password first, will give you a wrong result.

Why I get syntax error in this update statement?

I wanted to update a table in my m/s access database where my the user entered a new password in order to replace the old one but i have syntax error in the update statement. Please help!
public partial class resetPassword : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void SubmitButton_Click(object sender, EventArgs e)
{
string userName = (string) Session["username"];
string str = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\inetpub\wwwroot\JetStar\database\JetstarDb.accdb";
var con = new OleDbConnection(str);
con.Open();
string pwd = Request.Form["conPassword"];
OleDbCommand cmd = new OleDbCommand("UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'", con);
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Your password has been changed successfully.");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
con.Close();
}
}
}
Probably this happends because password is a reserved keyword on Microsoft Access. You should use it with square brackets as [password]
But more important
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Don't store your passwords as a plain text. Read: Best way to store password in database
Use using statement to dispose your OleDbConnection and OleDbCommand.
using(OleDbConnection con = new OleDbConnection(str))
using(OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = "UPDATE [users] SET [password] = ? WHERE username = ?";
cmd.Parameters.Add("pass", OleDbType.VarChar).Value = pwd;
cmd.Parameters.Add("user", OleDbType.VarChar).Value = userName;
con.Open();
try
{
cmd.ExecuteNonQuery();
MessageBox.Show("Your password has been changed successfully.");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
92.3% (a) of all DB problems become obvious if you just print the command before you use it, and read the error message.
So replace:
OleDbCommand cmd = new OleDbCommand("UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'", con);
with something like:
String s = "UPDATE [users] SET password = '" + pwd + "' WHERE username = '" + userName + "'";
Console.WriteLine(s);
OleDbCommand cmd = new OleDbCommand(s, con);
Then post the results of:
Response.Write(ex.Message);
for all to see, and examine what it tells you very carefully.
(a) A statistic I just plucked out of nowhere - actual value may be wildly different.

Change password not working

I have a web page where the user enters their current Username and Password. If they match a user in the database then the password is changed to the new password.
If there is no error and the password is changed the user is redirected to the initial login page. If there is an error then an error message will appear.
However at the moment the password is not changed and when there is supposed to be an error, i.e. when the the password was not changed, it just redirects the user anyway to the login page.
My code:
public static MySqlConnection CreateConnection()
{
String connectionString = "SERVER=127.0.0.1; DATABASE='dbnumericalmethods'; UID='root'; PASSWORD=''";
MySqlConnection SqlConnection = new MySqlConnection(connectionString);
return SqlConnection;
}
protected void btnChange_Click(object sender, EventArgs e)
{
MySqlConnection SqlConnection = CreateConnection();
string OldPassword;
string NewPassword;
string Username;
string ConfirmPassword;
Username = txtUsername2.Text;
OldPassword = txtOldPassword.Text;
NewPassword = txtNewPassword.Text;
ConfirmPassword = txtConfirmPassword.Text;
string SqlString = "update tblLogin set Identification='" + NewPassword + "' WHERE [Identification]='" + OldPassword + "' AND Username='" + Username + "'";
SqlConnection.Open();
MySqlCommand cmd = new MySqlCommand(SqlString, SqlConnection);
SqlConnection.Close();
if (OldPassword != "" && NewPassword != "" && ConfirmPassword != "")
{
Response.Redirect("Login.aspx");
}
else
{
lblErrorMessage2.Text = ("Username ");
}
}
You are not even executing the command, you are just opening the connection, creating a MySqlCommand then immediately close the connection:
MySqlCommand cmd = new MySqlCommand(SqlString, SqlConnection);
int result = cmd.ExecuteNonQuery();
SqlConnection.Close();
BTW, you should use parameterized queries to avoid SQL Injection.

C# Login screen using sql database not working

I have a simple login screen which, upon user clicking login button, should run the sql query to search for rows where the username == username text box, and password == password text box. This section of my code works fine.
However when I try to run an if statement, which will open a new form and close the login form, it errors, even though I have added some message boxes to check that the statement sting comparison is correct.
Any ideas?
Login Button:
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username='" + userText + "' and Password='" + passText + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
MessageBox.Show(userText + " / " + dr["Username"].ToString());
MessageBox.Show(passText + " / " + dr["Password"].ToString());
if (dr["Username"].ToString() == userText && dr["Password"].ToString() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Invalid Username or Password");
}
}
dr.Close();
cn.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Login attempt:
With the advice taken from the Answers and Comments below the code has been corrected to the following (using sql parameters in the sql command):
private void btnLogin_Click(object sender, EventArgs e)
{
try
{
string connection = #"Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\DebenhamsProjectOfficeDatabase.mdf;Integrated Security=True;User Instance=True";
SqlConnection cn = new SqlConnection(connection);
cn.Open();
string userText = txtUsername.Text;
string passText = txtPassword.Text;
SqlCommand cmd = new SqlCommand("SELECT ISNULL(Username, '') AS Username, ISNULL(Password,'') AS Password FROM Users WHERE Username = #username and Password = #password", cn);
cmd.Parameters.Add(new SqlParameter("username", userText));
cmd.Parameters.Add(new SqlParameter("password", passText));
SqlDataReader dr = cmd.ExecuteReader();
try
{
dr.Read();
if (dr["Username"].ToString().Trim() == userText && dr["Password"].ToString().Trim() == passText)
{
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
}
catch
{
MessageBox.Show("Invalid Username or Password");
}
dr.Close();
cn.Close();
}
try adding a trim() on to the end of the sql return as you check them.
dr["Username"].ToString().trim() and dr["Password"].ToString().trim()
Sometimes the Database will store extra spaces you cant see.
Simply try this: I think it will work
SqlCommand cmd = new SqlCommand("SELECT * FROM Users WHERE Username='" + userText.toString() + "' and Password='" + passText.toString() + "'", cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
MessageBox.Show(username + " / " + usertext);
MessageBox.Show(password + " / " + passtext);
this.Hide();
Dashboard dashboard = new Dashboard();
dashboard.ShowDialog();
this.Close();
}
else
{
MessageBox.Show("Invalid Username or Password");
}

Categories