Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public Form1()
- {
- server = "localhost";
- database = "tut1";
- uid = "root";
- password = "";
- string connString;
- connString = $"SERVER={server};DATABASE={database};UID={uid};PASSWORD={password};";
- conn = new MySqlConnection(connString);
- InitializeComponent();
- }
- private void Form1_Load(object sender, EventArgs e)
- {
- }
- private void btnRegister_Click(object sender, EventArgs e)
- {
- string user = tbUser.Text;
- string pass = tbPass.Text;
- if (Register(user, pass))
- {
- MessageBox.Show($"User {user} has been created!");
- }
- else
- {
- MessageBox.Show($"User {user} has not been created!");
- }
- }
- private void btnLogin_Click(object sender, EventArgs e)
- {
- string user = tbUser.Text;
- string pass = tbPass.Text;
- if (IsLogin(user, pass))
- {
- MessageBox.Show($"Welcome {user} !");
- }
- else
- {
- MessageBox.Show($"User {user} does not exists or password is incorrect!");
- }
- }
- public bool Register(string user, string pass)
- {
- string query = $"INSERT INTO users (id, username, password) VALUES ('', '{user}', '{pass}');";
- try
- {
- if (OpenConnection())
- {
- MySqlCommand cmd = new MySqlCommand(query, conn);
- try
- {
- cmd.ExecuteNonQuery();
- return true;
- }
- catch (Exception ex)
- {
- return false;
- }
- }
- else
- {
- conn.Close();
- return false;
- }
- }
- catch (Exception ex)
- {
- conn.Close();
- return false;
- }
- }
- public bool IsLogin(string user, string pass)
- {
- string query = $"SELECT * FROM users WHERE username ='{user}' AND password = '{pass}';";
- try
- {
- if (OpenConnection())
- {
- MySqlCommand cmd = new MySqlCommand(query, conn);
- MySqlDataReader reader = cmd.ExecuteReader();
- if (reader.Read())
- {
- reader.Close();
- conn.Close();
- return true;
- }
- else
- {
- reader.Close();
- conn.Close();
- return false;
- }
- }
- else
- {
- conn.Close();
- return false;
- }
- } catch (Exception ex)
- {
- conn.Close();
- return false;
- }
- }
- private bool OpenConnection()
- {
- try
- {
- conn.Open();
- return true;
- }
- catch (MySqlException ex)
- {
- switch (ex.Number)
- {
- case 0:
- MessageBox.Show("Connection to the server failed!");
- break;
- case 1045:
- MessageBox.Show("Server username or password is incorrect");
- break;
- }
- return false;
- }
- }
- }
Add Comment
Please, Sign In to add comment