Java如何从数据库获取所有表名?

package org.nhooo.example.jdbc;

import java.sql.*;

public class GettingTableListExample {

    private static final String URL = "jdbc:mysql://localhost/nhooo";

    private static final String USERNAME = "root";

    private static final String PASSWORD = "";

    public static void main(String[] args) throws Exception {

        try (Connection connection =

                 DriverManager.getConnection(URL, USERNAME, PASSWORD)) {

            // 获取数据库的元数据

            DatabaseMetaData metaData = connection.getMetaData();

            String[] types = {"TABLE"};

            ResultSet rs = metaData.getTables(null, null, "%", types);

            while (rs.next()) {

                String tableCatalog = rs.getString(1);

                String tableSchema = rs.getString(2);

                String tableName = rs.getString(3);

                System.out.printf("%s - %s - %s%n",

                    tableCatalog, tableSchema, tableName);

            }

        }

    }

}

结果如下:

nhooo - null - authors

nhooo - null - book_authors

nhooo - null - books

Maven依赖

<!-- https://search.maven.org/remotecontent?filepath=mysql/mysql-connector-java/8.0.17/mysql-connector-java-8.0.17.jar -->

<dependency>

    <groupId>mysql</groupId>

    <artifactId>mysql-connector-java</artifactId>

    <version>8.0.17</version>

</dependency>

以上是 Java如何从数据库获取所有表名? 的全部内容, 来源链接: utcz.com/z/340727.html

回到顶部