C# connect to MySQL database - use MySql.Data.dll

The premise of using the MySQL database is that the MYSQL database is installed on the computer before you can use it.

1. Download MySql.Data.dll, MySql.Web.dll

MySql.Data.dll and MySql.Web.dll are the driver files for C# to operate MySQL, and are necessary plug-ins for C# to connect to MySQL.

2. Create a new windows form application.

Create a new windows form application MySQLConnectionTest, add a DataGridView on the interface, the default name is: dataGridView1.
write picture description here

3. Add MySql.Data.dll, MySql.Web.dll reference.

Select the project MySQLConnectionTest in the solution explorer -> right click -> add reference
write picture description here

In the pop-up dialog box, select Browse -> Find MySql.Data.dll, MySql.Web.dll file and select the two files, click the OK button.
write picture description here

After adding the reference successfully, you can view the two dll files in the reference
write picture description here

4. Add code implementation.

Double-click the Form1 form to enter the Form1.cs code interface, add code in the Form1_Load function to connect to the database and display data information.

Note: You need to build the database select_test in the MYSQL database, and the table teacher_table in the database select_test.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;//添加mysql引用
using System.Diagnostics;

namespace MySQLConnectionTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //构建数据库连接字符串
            string M_str_sqlcon = "server=localhost;user id=root;password=root;database=select_test"; //根据自己的设置
            //创建数据库连接对象
            MySqlConnection mycon = new MySqlConnection();
            mycon.ConnectionString = M_str_sqlcon;
            try
            {
                //打开数据库连接
                mycon.Open();
                MessageBox.Show("数据库已经连接了!");
                string sql = "select * from teacher_table";
                MySqlDataAdapter mda = new MySqlDataAdapter(sql, mycon);
                DataSet ds = new DataSet();
                mda.Fill(ds, "table1");
                //显示数据
                this.dataGridView1.DataSource = ds.Tables["table1"];
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
                Debug.Write(ex);
            }
            //关闭数据库连接
            mycon.Close();
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325746248&siteId=291194637