如何使用 JDBC 获取所有数据库的列表?
可以使用 SHOW DATABASES 查询获取 MySQL 中的数据库列表。
show databases;
以下 JDBC 程序通过执行显示数据库查询来检索数据库列表。
示例
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.Statement; public class ShowDatabasesExample { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating a Statement object Statement stmt = con.createStatement(); //Retrieving the data ResultSet rs = stmt.executeQuery("Show Databases"); System.out.println("List of databases: "); while(rs.next()) { System.out.print(rs.getString(1)); System.out.println(); } } }
输出
Connection established...... List of databases: information_schema base details errors logging mydatabase mydb mysql performance_schema sample_database sampledb students sys testdb world
或者,可以使用 DatabaseMetaData 接口的 getCatalogs() 方法。
示例
import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.DriverManager; import java.sql.ResultSet; public class ListOfAllDatabases { public static void main(String args[]) throws Exception { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://127.0.0.1/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Retrieving the meta data object DatabaseMetaData metaData = con.getMetaData(); //Retrieving the list of database names ResultSet tables = metaData.getCatalogs(); while (tables.next()) { System.out.println(tables.getString("TABLE_CAT")); } } }
输出
Connection established...... List of databases: information_schema base details errors logging mydatabase mydb mysql performance_schema sample_database sampledb students sys testdb world
广告