简体   繁体   中英

how to get list of Databases "Schema" names of MySql using java JDBC

如何使用java JDBC获取MySql的数据库“架构”名称列表?

The getSchemas() method of the DatabaseMetaData is the obvious but with MySQL you have to use getCatalogs()

http://download.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#getSchemas() http://download.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#getCatalogs()

Example:

Class.forName("com.mysql.jdbc.Driver");

// change user and password as you need it
Connection con = DriverManager.getConnection (connectionURL, "user", "password");

ResultSet rs = con.getMetaData().getCatalogs();

while (rs.next()) {
    System.out.println("TABLE_CAT = " + rs.getString("TABLE_CAT") );
}
  • Either use SHOW DATABASES to see if it is inside,
  • Check the INFORMATION_SCHEMA,
  • or just do USE DATABASE; and catch the error.
DatabaseMetaData meta = conn.getMetaData();
ResultSet schemas = meta.getSchemas();
while (schemas.next()) {
  String tableSchema = schemas.getString(1);    // "TABLE_SCHEM"
  String tableCatalog = schemas.getString(2); //"TABLE_CATALOG"
  System.out.println("tableSchema "+tableSchema);
}
DatabaseMetaData dbmd = con.getMetaData();
ResultSet ctlgs = dbmd.getCatalogs();
while(ctlgs.next())
{
System.out.println("ctlgs  =  "+ctlgs.getString(1));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM