using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;

namespace mysql
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // 1. 定义连接字符串
            string connectionString = "server=localhost;port=3307;database=testdb;uid=root;pwd=3101;";

            // 2. 使用 using 语句确保资源被正确释放
            using (MySqlConnection connection = new MySqlConnection(connectionString))
            {
                try
                {
                    // 3. 打开连接
                    connection.Open();
                    Console.WriteLine("数据库连接成功!");

                    // 4. 执行查询
                    string sql = "SELECT * FROM student";
                    MySqlCommand command = new MySqlCommand(sql, connection);
                    using (MySqlDataReader reader = command.ExecuteReader())
                    {
                        // 5. 读取结果
                        while (reader.Read())
                        {
                            // 假设表中有 Id 和 Name 两列
                            Console.WriteLine($"Id: {reader["Id"]}, Name: {reader["Name"]}");
                        }
                    }
                }
                catch (MySqlException ex)
                {
                    Console.WriteLine($"连接错误: {ex.Message}");
                }
            }
        }
    }
}

记得安装 NuGet包

MySql.Data

更多推荐