I've built a class that handles all my connections to a MySql database.
These are the function I use to create the connection(not really sure about the two dispose functions) :
public class dbConnection : IDisposable
{
public MySqlConnection conn;
public MySqlTransaction transaction;
private static Logger logger = LogManager.GetCurrentClassLogger();
public dbConnection()
{
string host = "1.1.1.1";
string usernameMySql = "admin";
string pswMySql = "password";
string nomeDb = "db1";
string connStr = "Database=" + nomeDb + ";" +
"Data Source=" + host + ";" +
"User Id=" + usernameMySql + ";Password=" + pswMySql + "";
conn = new MySqlConnection(connStr);
}
public void openConnection()
{
conn.Close();
conn.Open();
transaction = conn.BeginTransaction();
}
public void closeConnection()
{
transaction.Commit();
conn.Close();
}
protected virtual void Dispose(Boolean disposing)
{
if (disposing)
{
}
}
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
These are the functions I use to read/write data:
public void ExecuteSQL(string sSql)
{
MySqlCommand cmd = new MySqlCommand(sSql, conn);
cmd.ExecuteNonQuery();
}
public MySqlDataReader readerSQL(string sSql)
{
MySqlCommand cmd = new MySqlCommand(sSql, conn);
MySqlDataReader readerSql = cmd.ExecuteReader();
return readerSql;
}
protected int ExecuteSQLReturnId(string sSql)
{
MySqlCommand cmd = new MySqlCommand(sSql, conn);
cmd.ExecuteNonQuery();
return Convert.ToInt32(cmd.LastInsertedId);
}
In others part of my project i then use
db = new dbConnection();
db.openConnection();
to create a new connection.
This code works but I'm not really sure it's the right way to handle things, Are there any improvements that can be made ?