I am trying to connect to a mysql database, my credentials(username, password, database name… etc) are all correct to my knowledge. I got stuck at coonection.open() statement which displays an error of the connection being already opened.
I searched for help at other sites, it has been reported as a bug… http://support.microsoft.com/kb/823401
While searching for alternative solutions I came across
using ( connection = MySqlConnection(connectionString))
I was unable to proceed with it. Any help with it would be really appreciated.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MySql.Data.MySqlClient;
using System.Windows.Forms;
namespace HotelManagement
{
class DBConnect
{
private MySqlConnection connection;
private string server;
private string database;
private string uid;
private string password;
//constructor
public DBConnect()
{
Initialize();
}
private void Initialize()
{
server = "localhost";
database = "hm";
uid = "root";
password = "password";
string connectionString;
connectionString = "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
connection = new MySqlConnection(connectionString);
}
public bool openConnection()
{
try
{
connection.Open(); //*SHOWS ERROR InvalidOperationUnhandled: Conection already open*
return true;
}
catch (MySqlException e)
{
//error 0: Cannot Connect to the server
switch (e.Number)
{
case 0: MessageBox.Show("Cannot Connect to the server");
break;
case 1045: MessageBox.Show("invalid username/password");
break;
}
return false;
}
}
public bool closeConnection()
{
try
{
connection.Close();
return true;
}
catch (MySqlException e)
{
MessageBox.Show(e.Message);
return false;
}
}
public void insert()
{
string query = "insert into test (i) values (10)";
if (this.openConnection() == true)
{
//creating command and connections
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
this.closeConnection();
}
}
}
}
You must close your connection , you have not closed connection (Maybe after first debug)
You can use
Best Practise :
I suggest you to use using block, in order to ensure that you clean non managed object in the end of treatment