⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Working with MySQL in C#

I hope this publication will not give readers the opportunity to repeat my mistakes and help make the initial correct choice. First, I would like to start with a strong recommendation: "When programming under .NET, always use MySQL .NET Connector!". Of course, you can connect to the database using ADO, but this is fraught with the fact that you will simply need to make changes when switching to Windows Vista and above.



A small digression: MySQL is very convenient to use when programming for mobile devices based on Windows. Standard libraries work and on a mobile device under .NET CF exactly as on a server or workstation. (It is meant for cases where you need to access a database on a server from a mobile computer. You cannot install a MySQL server on a mobile device.) And in addition. I strongly do not recommend using SQL.CE for large databases (over 50,000 records in a table) on a mobile device, as performance drops significantly with growing database size. In my opinion, it is much better to think through your data storage system. But this will be in a separate publication.

To work with MySQL, you will need "MySQL Connector / NET".

http://dev.mysql.com/downloads/connector/net/5.2.html
To be able to work with the database, download and install the utility.



Next, open your project and connect MySQL Connector:

Project->Add references->.NET->MySQL.Data
After which, in the Solution Explorer, the MySQL.Data reference should appear in the References section.



Be sure to specify in the project:

using MySql.Data.MySqlClient;



Creating a connection to the database:

string CommandText = "Наш SQL скрипт";
string Connect="Database=БАЗА;Data Source=ХОСТ;User Id=ПОЛЬЗОВАТЕЛЬ;Password=ПАРОЛЬ";
//Переменная Connect - это строка подключения в которой:
//БАЗА - Имя базы в MySQL
//ХОСТ - Имя или IP-адрес сервера (если локально то можно и localhost)
//ПОЛЬЗОВАТЕЛЬ - Имя пользователя MySQL
//ПАРОЛЬ - говорит само за себя - пароль пользователя БД MySQL
MySqlConnection myConnection = new MySqlConnection(Connect);
MySqlCommand myCommand = new MySqlCommand(CommandText, myConnection);
myConnection.Open(); //Устанавливаем соединение с базой данных.
//Что то делаем...
myConnection.Close(); //Обязательно закрываем соединение!



The point "//What we do..." may differ depending on whether we are doing a selection or making changes to the database.



Case one: we are doing a selection:



A selection can be of two types: when the query returns one value and when the query returns a set of values. You can process them differently.



If the query returns one value (you need to be sure that the query will return exactly one value, otherwise there will be an error).

string znachenie = MyCommand.ExecuteScalar().ToString();



If the query returns a set of values, then:

MySqlDataReader MyDataReader;
MyDataReader = myCommand.ExecuteReader();

            while (MyDataReader.Read())
            {
                string result = MyDataReader.GetString(0); //Получаем строку
                int id = MyDataReader.GetInt32(1); //Получаем целое число
            }
MyDataReader.Close();



Case two: we are making changes:



To execute a script that changes data, use:

MyCommand.ExecuteNonQuery();



That's it, the rest is easy to figure out yourself.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.