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

时间:2011-04-15 15:48:33

标签: java mysql database list jdbc

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

4 个答案:

答案 0 :(得分:19)

DatabaseMetaData的getSchemas()方法很明显但是使用MySQL你必须使用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()

示例:

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") );
}

答案 1 :(得分:4)

  • 使用SHOW DATABASES查看是否 它在里面,
  • 检查INFORMATION_SCHEMA,
  • 或只是做USE DATABASE;并抓住 错误。

答案 2 :(得分:3)

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);
}

希望这个帮助

答案 3 :(得分:0)

DatabaseMetaData dbmd = con.getMetaData();
ResultSet ctlgs = dbmd.getCatalogs();
while(ctlgs.next())
{
System.out.println("ctlgs  =  "+ctlgs.getString(1));
}