How to connect to a MySQL database using C#?

To connect to a MySQL database in C#, you can use MySQL Connector/Net, which is the official MySQL-provided database driver for the .NET platform. Here are the steps to connect to a MySQL database:

  1. Firstly, download and install the MySQL Connector/Net driver. The latest version of MySQL Connector/Net can be downloaded and installed from the official MySQL website.
  2. In a C# project, add a reference to MySQL Connector/Net. Right-click on the project -> Add -> Reference -> Browse -> Select the MySQL.Data.dll file located in the installation path of MySQL Connector/Net.
  3. Write code in C# to connect to a MySQL database. Here is a simple example:
using System;
using MySql.Data.MySqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "server=localhost;user id=root;password=your_password;database=your_database";

        MySqlConnection connection = new MySqlConnection(connectionString);

        try
        {
            connection.Open();
            Console.WriteLine("Connected to MySQL database!");

            // 在这里可以执行数据库操作

            connection.Close();
        }
        catch (MySqlException ex)
        {
            Console.WriteLine("Error: " + ex.Message);
        }
    }
}

In the example above, a connection string is first created that includes the address, username, password, and database name of the MySQL database. Then a MySqlConnection object is created and the connection is opened. After the connection is successful, the necessary database operations can be executed before closing the connection.

In this way, you can connect to a MySQL database and perform database operations in C#. It is important to note that the address, username, password, and database name in the connection string need to be replaced according to the actual situation.

bannerAds