Connect to MySQL database using C#

problem

Connect to MySQL database using C# and Visual Studio. This blog post is about using the connection string to connect to a local MySQL database and read data and print them in the console.

The tutorial was written using the official IDE from Microsoft –Visual Studio.

No longer available. Check out this link for alternatives.

create project
new project in visual studio for Mac OS (unavailable from 2024 and onwards)

Create a Console Application

add dependency
add mysql dependency (visual studio for Mac OS (unavailable from 2024 and onwards)

MySql.Data package is needed

connect to database

Now let’s put the code to connect to the MySQL db instance and read some data. A local MySQL instance is running with the database and table already created.

				
					using System;
using MySql.Data.MySqlClient;

namespace mysqlTest
{
    public class MySQLReader
    {
        public static void Main()
        {
            string connectionString = "server=localhost;user=root;database=test;";
            MySqlConnection connection = new MySqlConnection(connectionString);

            try
            {
                Console.WriteLine("Connecting to MySQL...");
                connection.Open();

                string sql = "SELECT * FROM users";
                MySqlCommand cmd = new MySqlCommand(sql, connection);
                MySqlDataReader reader = cmd.ExecuteReader();

                while (reader.Read())
                {
                    Console.WriteLine(reader[0] + " -- " + reader[1]);
                }
                reader.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }

            connection.Close();
            Console.WriteLine("Done.");
        }
    }
}
				
			

The code above connects to a database named test and reads all the rows from the table users. It’s printing in the console the first two fields/ columns of each record. Also, the connection string above has no password provided for simplicity. The user: root didn’t setup password at installation phase of MySQL (which is discouraging).

output
c# output of mysql connection and read

Current db with user table and a record having 4 columns (fields)

running

Executing the code above shows the following output in the console.

C# mysql database read example

Correct!

Crash test

The reader[0] + ” — ” + reader[1] is shown above. If we were to run it with reader[5] or any index greater than 3 it should crash and the catch exception clause should catch it and print the error.

Let’s try updating the line below:

				
					Console.WriteLine(reader[0] + " -- " + reader[1]);
				
			

to

				
					Console.WriteLine(reader[3] + " -- " + reader[4]);
				
			

and by running it..breaks!

mysql read error in C# example

As expected with IndexOutOfRangeException (4 columns are indexed from 0 to 3 inclusive).

conclusion

In this post, the code simply connects and reads data from the table specified in a local database. This code can be adapted to your database and table names, also the server can be a remote IP address instead of localhost.

Share it!

Facebook
Twitter
LinkedIn
Reddit
Picture of Ellion

Ellion

Professional IT consultant, writer, programmer enthusiast interested in all sorts of coding.
Eats all cookies 🍪

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x
Privacy Overview

This website uses cookies so that we can provide you with the best user experience possible. Cookie information is stored in your browser and performs functions such as recognising you when you return to our website and helping our team to understand which sections of the website you find most interesting and useful.

Strictly Necessary Cookies

Strictly Necessary Cookie should be enabled at all times so that we can save your preferences for cookie settings.

Google Analytics Cookies

This website uses Google Analytics to collect anonymous information such as the number of visitors to the site, and the most popular pages.

Keeping this cookie enabled helps us to improve our website.

HotJar Cookies

We use Hotjar in order to better understand our users’ needs and to optimize this service and experience. Hotjar is a technology service that helps us better understand our users’ experience (e.g. how much time they spend on which pages, which links they choose to click, what users do and don’t like, etc.) and this enables us to build and maintain our service with user feedback. Hotjar uses cookies and other technologies to collect data on our users’ behavior and their devices. This includes a device's IP address (processed during your session and stored in a de-identified form), device screen size, device type (unique device identifiers), browser information, geographic location (country only), and the preferred language used to display our website. Hotjar stores this information on our behalf in a pseudonymized user profile. Hotjar is contractually forbidden to sell any of the data collected on our behalf.

For further details, please see the ‘about Hotjar’ section of Hotjar’s support site.