下面的示例向您展示如何在MySQL数据库中获取可用的目录名称。可以DatabaseMetaData通过调用getCatalogs()方法从对象获得可用的目录名称。此方法返回一个ResultSet对象。我们对其进行迭代,并通过调用getString()方法获得模式名称,并将其TABLE_CAT作为列名称传递。
package org.nhooo.example.jdbc; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; public class MetadataGetCatalog { private static final String URL = "jdbc:mysql://localhost"; private static final String USERNAME = "root"; private static final String PASSWORD = ""; public static void main(String[] args) { try (Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD)) { // 获取DatabaseMetaData DatabaseMetaData metadata = connection.getMetaData(); // 检索此数据库中可用的架构名称 ResultSet rs = metadata.getCatalogs(); while (rs.next()) { String catalog = rs.getString("TABLE_CAT"); System.out.println("Catalog: " + catalog); } } catch (SQLException e) { e.printStackTrace(); } } }
这里是MySQL数据库中可用的目录名称列表:
Catalog: nhooo Catalog: mediadb Catalog: mysql Catalog: performance_schema Catalog: sys
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>