Enzo Enzo

Enzo Enzo

  • NA
  • 26
  • 2.6k

login form mysql problem

Jan 17 2017 7:26 PM
Form1.cs 
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace test
{
public partial class Form1 : Form
{
private DBConnect dbConnect;
public Form1()
{
InitializeComponent();
dbConnect = new DBConnect();
}
private void submit_Click_1(object sender, EventArgs e)
{
string user = txtusername.Text;
string pass = txtpassword.Text;
if (user == "" || pass == "")
{
MessageBox.Show("Empty Fields Detected ! Please fill up all the fields");
return;
}
bool r = dbConnect.Login(user, pass);
if (r)
MessageBox.Show("Correct Login Credentials");
else
MessageBox.Show("Incorrect Login Credentials");
}
}
}
 
 
DBConnect.cs 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace test
{
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//Constructor
public DBConnect()
{
Initialize();
}
//Initialize values
private void Initialize()
{
server = "localhost";
database = "connectcsharptomysql";
uid = "root";
password = "admin1234";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
internal bool Login(string user, string pass)
{
MySqlCommand cmd = new MySqlCommand();
cmd.CommandText = "Select * from users where username=@user and pass=@pass";
cmd.Parameters.AddWithValue("@user", user);
cmd.Parameters.AddWithValue("@pass", pass);
cmd.Connection = connection;
MySqlDataReader users = cmd.ExecuteReader();
if (users.Read())
{
connection.Close();
return true;
}
else
{
connection.Close();
return false;
}
}
//open connection to database
private bool OpenConnection()
{
try
{
connection.Open();
return true;
}
catch (MySqlException ex)
{
//When handling errors, you can your application's response based on the error number.
//The two most common error numbers when connecting are as follows:
//0: Cannot connect to server.
//1045: Invalid user name and/or password.
switch (ex.Number)
{
case 0:
MessageBox.Show("Cannot connect to server. Contact administrator");
break;
case 1045:
MessageBox.Show("Invalid username/password, please try again");
break;
}
return false;
}
}
//Close connection
private bool CloseConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
return false;
}
}
}
}
 

Answers (3)