以下是使用 C# 连接 MySQL 查询指定数据库所有表名并打印每个表的第一行数据的示例代码:

using System;
using MySql.Data.MySqlClient;

namespace ConsoleApp
{
    class Program
    {
        static void Main(string[] args)
        {
            string connectionString = "server=localhost;user=root;password=123456;database=mydatabase";
            MySqlConnection connection = new MySqlConnection(connectionString);
            MySqlCommand command = connection.CreateCommand();
            command.CommandText = "SHOW TABLES";
            connection.Open();
            MySqlDataReader reader = command.ExecuteReader();

            while (reader.Read())
            {
                string tableName = reader.GetString(0);
                Console.WriteLine("Table: " + tableName);

                MySqlCommand selectCommand = connection.CreateCommand();
                selectCommand.CommandText = "SELECT * FROM " + tableName + " LIMIT 1";
                MySqlDataReader tableReader = selectCommand.ExecuteReader();

                while (tableReader.Read())
                {
                    for (int i = 0; i < tableReader.FieldCount; i++)
                    {
                        Console.Write(tableReader.GetValue(i) + "\t");
                    }
                    Console.WriteLine();
                }
                tableReader.Close();
            }

            reader.Close();
            connection.Close();
            Console.ReadLine();
        }
    }
}

以上代码使用 MySqlConnectionMySqlCommand 类连接 MySQL 数据库并执行 SQL 语句。首先执行 SHOW TABLES 可以获取指定数据库中所有表名,然后遍历每个表名并执行 SELECT * FROM table LIMIT 1 获取每个表的第一行数据并打印。最后关闭数据库连接

C# 连接mysql查询指定数据库所有表名并且打印每个表的第一行数据

原文地址: https://www.cveoy.top/t/topic/hqZA 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录