I am new in Programming line please give me the code to connect Mysql Database with C# in windows Form.
I made a program of login and i create a Mysql databse but when i goes to connect the form with database& written whole code i encounter a problem That "error with database connection" and it show exception in code line
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
namespace Login
{
public partial class Form1 : Form
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
public Form1()
{
InitializeComponent();
}
private void Initialize()
{
server = "localhost";
database = "diary";
uid = "root";
password = "12345";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" +
database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
private void button1_Click(object sender, EventArgs e)
{
try
{
connection.Open();
string qry1 = "Select * from login where Password=@Password and Username=@Username";
MySqlCommand com = new MySqlCommand(qry1, connection);
com.Parameters.AddWithValue("@Username", this.textBox1.Text);
com.Parameters.AddWithValue("@Password", this.textBox2.Text);
MySqlDataReader dr = com.ExecuteReader();// this line show the exception....
while (dr.Read())
{
if (dr.HasRows == true)
{
MessageBox.Show("Login Successfull", "Login Information");
this.Hide();
home h = new home();
h.Show();
}
}
if (dr.HasRows == false)
{
MessageBox.Show("Access Denied", "Login Information");
this.Close();
}
connection.Close();
}
catch (Exception)
{
MessageBox.Show("Error with the database connection");
}
}
private void label3_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}