如何使用JDBC获取所有数据库的列表?
您可以使用SHOW DATABASES查询获取MySQL中的数据库列表。
show databases;
以下JDBC程序通过执行show database查询来检索数据库列表。
示例
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 {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获得连接
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//创建一个Statement对象
Statement stmt = con.createStatement();
//检索数据
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 {
//注册驱动程序
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//获得连接
String mysqlUrl = "jdbc:mysql://localhost/mydatabase";
Connection con = DriverManager.getConnection(mysqlUrl, "root", "password");
System.out.println("Connection established......");
//检索元数据对象
DatabaseMetaData metaData = con.getMetaData();
//检索数据库名称列表
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
以上是 如何使用JDBC获取所有数据库的列表? 的全部内容, 来源链接: utcz.com/z/352503.html