如何获取Mysql数据库中所有表名

版权声明:此文由黑夜の骑士创作,转载请注明出处,交流qq1056291511 https://blog.csdn.net/birdfly2015/article/details/88131651

背景

小伙伴们在使用数据库时,有时候不止需要访问其中的一个表,而是多个表,这个时候就需要首先获取数据库中的表名,然后循环读取表了。

思路

sql语句:show tables from 数据库名

代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace _01获得mysql数据库表名
{
    class Program
    {
        static void Main(string[] args)
        {
            String connetStr = "server=127.0.0.1;port=3306;user=root;password=密码; database=数据库名称;";
            MySqlConnection conn = new MySqlConnection(connetStr);//连接数据库
            List<String> Tablenames = new List<String>();//建立一个列表,来存储数据库里面的所有表名
            try
            {
                conn.Open();//打开通道,建立连接,可能出现异常,使用try catch语句
                Console.WriteLine("已经建立连接");
                //在这里使用代码对数据库进行增删查改
                string query = "show tables from 数据库名";
                MySqlCommand command = new MySqlCommand(query, conn);
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Tablenames.Add(reader.GetString(0));//将表名添加到定义好的列表中来
                        Console.WriteLine(reader.GetString(0));  //这儿就会打印出每一个数据库的表名了
                    }
                }
            }
            catch (MySqlException ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                conn.Close();
            }
        }
    }
}

注意

本文只给出了如何获取表名的方法,如何遍历这些表,小伙伴们结合读取一个表,然后循环就Ok了。

猜你喜欢

转载自blog.csdn.net/birdfly2015/article/details/88131651