我试图用Java列出MySQL数据库及其表。目前,我有&#34; Database_Services 两个数据库, MySQL_Database_Service , MSSQL_Database_Service , Directory_Services 带< em> Active_Directory , OpenLDAP 表。我得到了 Database_Services 及其表格的输出,但我没有得到其他的。
public class connectMySQL implements serverConnection{
Connection conn;
Statement stmt;
public void connect(String dbName){
String url;
try {
if(dbName.equals("")){
url = "jdbc:mysql://x:x/";
}
else{
url = "jdbc:mysql://x:x”+ dbName;
}
String username = “x”;
String password = "x";
conn = DriverManager.getConnection(url,username,password);
stmt = conn.createStatement();
}
catch (SQLException ex)
{
System.out.println("An error occurred. Maybe user/password is invalid");
ex.printStackTrace();
}
}
}
public class listInf extends connectMySQL implements listInfrastructure {
public void list() {
String dbName;
ResultSet rs;
try{
connect("");
String str = "SHOW DATABASES";
ResultSet resultSet = stmt.executeQuery(str);
while(resultSet.next()){
dbName = resultSet.getString("Database");
if(!dbName.contains("schema") && !dbName.equals("mysql")){
System.out.println(dbName);
rs = stmt.executeQuery("SHOW TABLES IN " + dbName);
while (rs.next()) {
System.out.println("\t" + rs.getString("Tables_in_" + dbName));
}
}
}
}
catch(SQLException e){
System.out.println("Error");
}
}
}
我希望获得如下输出:
Database_Services:
Directory_Services:
Active_Directory_Service。
OpenLDAP_Service。
答案 0 :(得分:1)
您对多个查询使用相同的Statement
。你不能这样做。来自Javadoc of Statement
:
默认情况下,每个Statement对象只能同时打开一个ResultSet对象。因此,如果读取一个ResultSet对象与另一个ResultSet对象的读取交错,则每个ResultSet对象必须由不同的Statement对象生成。 Statement接口中的所有执行方法都隐式关闭一个语句的当前ResultSet对象(如果存在一个打开的对象)。
答案 1 :(得分:0)
Connection conn1 = DriverManager.getConnection(url, username, password);
Connection conn2 = DriverManager.getConnection(url, username, password);
Statement statement1 = conn1.createStatement();
Statement statement2 = conn2.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SHOW TABLES IN DB1");
ResultSet resultSet2 = statement2.executeQuery("SHOW TABLES IN DB2");
while (resultSet1.next()) {
System.out.println("");
}
while (resultSet2.next()) {
System.out.println("");
}
如果您有超过2个数据库,那么只需使用循环即可获得结果。
答案 2 :(得分:0)
您可以使用元信息数据库information_schema
。
SELECT
TABLE_SCHEMA,
TABLE_NAME
FROM information_schema.TABLES
WHERE TABLE_SCHEMA IN ('Database_Services', 'Directory_Services')
ORDER BY TABLE_SCHEMA