In the applications I currently write, I deal a lot with a couple of MySql databases. I know I am doing this the wrong way, so you don't need to tell me that, but how do I do this the correct way? As in, what is the correct practice for dealing with a MySql database from a .Net application.
At the minute I use a class, which is below:
using System;
using MySql.Data.MySqlClient;
namespace WhateverProjectImWorkingOn
{
class MySql
{
public string myConnectionString = String.Format("SERVER={0}; DATABASE={1}; UID={2}; PASSWORD={3}", "8.8.8.8", "foobar", "foo", "barr");
public string Select(string mySqlQuery)
{
MySqlConnection connection = new MySqlConnection(myConnectionString);
MySqlCommand command = connection.CreateCommand();
MySqlDataReader Reader;
command.CommandText = mySqlQuery;
connection.Open();
Reader = command.ExecuteReader();
string thisrow = "";
while (Reader.Read())
{
for (int i = 0; i < Reader.FieldCount; i++)
{
thisrow += Reader.GetValue(i).ToString();
}
}
Reader.Close();
connection.Close();
return thisrow;
}
public void Update(string mySqlQuery)
{
MySqlConnection mangoConnection = new MySqlConnection(myConnectionString);
MySqlCommand command = mangoConnection.CreateCommand();
command.CommandText = mySqlQuery;
mangoConnection.Open();
MySqlDataReader reader = command.ExecuteReader();
mangoConnection.Close();
}
}
}
I instanciate this class and then use the Select method to select data like so:
MySql mySql = new MySql();
string whateverIWant = mySql.Select("Select `MyValue` From `FooBarr` Where `Foo` = 'Barr'");
I run update queries like so:
mySql.Update("UPDATE `tblFooBarr` SET `acme`='Foo' WHERE `tnt`='barr';");
Before you start, yes I am thoroughly ashamed of myself for my sloppy sloppy code, but if you could help me improve I would be most appreciative!
Thanks