Recently, i’ve been coding some stuff that interacts with mysql from C#, and its taken me quite a long time to get some basic stuff working. Here is a basic tutorial to get the stuff working basicly (ie; connecting to database, reading results from rows.).
Ok, first get MySQL Connector .NET. Add it as a reference via Visual Studio, and add “using MySql.Data.MySqlClient;” to the top of your application.
Now, to get to the bones of it. The basic connect strings i have been using are:
1: conDatabase = new MySqlConnection(“server=brentp.net; user id=bah; password=bahblacksheep; database=haveyouany; pooling=false;”);
That connects us to the database.
MySqlConnection conDatabase = new MySqlConnection(“server=faklas.net; user id=wha; password=asf; database=asfasfa; pooling=false;”); string Query = “SELECT * FROM `blah`”; conDatabase.Open(); MySqlCommand cmd = new MySqlCommand(Query, conDatabase); MySqlDataReader read = cmd.ExecuteReader(); while (read.Read()) { if (read[0].ToString() == “whatever”) // do something } } read.Close(); conDatabase.Close();
Thats all the code there that allows us to connect to the database, read a result and do something depending on what it says. read[0] is the first result from the dataset, (if its easier to you, you can use the name of the column, rather than the index of the row). This can be made more efficent if you use it multiple times. If you wish to execute a command where you wish to get no feedback (insert, update, delete), you just use:
string strDelete = “INSERT DELETE OR UPDATE COMMAND HERE.”; // CONNECT HERE. MySqlCommand cmdDatabase = new MySqlCommand(strDelete, conDatabase); conDatabase.Open(); try { cmdDatabase.ExecuteNonQuery(); } catch (MySqlException mye) { MessageBox.Show(mye.ToString(), “Error:”, MessageBoxButtons.OK, MessageBoxIcon.Error); } conDatabase.Close();
Note: You can use ‘int bleh = cmdDatabase.ExecuteNonQuery();’ then ‘rowsc.ToString()’ for the number of rows changed with the query to see if it worked or not. Of course, you could do better error handling than what i included here (ie; checking if you actually connected to the db, because if you didnt, the application would throw an exception and crash. Easy way to fix this would to try, catch and finally. Thats all i have for tonight, gotta find something to do before alias starts at 12:30 (assuming the tennis doesnt run over again. Goddamn channel 7 and their sports coverage). Enjoy.
PS: check out violentacres.com.