10

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

0

4 Answers 4

20

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") );
}
Sign up to request clarification or add additional context in comments.

3 Comments

JDBC allows to access Schemas and Catalogs but it's meaning is a bit DBMS specific and some provide both while others just one and not always with the method you'd first suspect...
If the MySQL server is running on Windows, this code prints the database names in lowercase. This may or may not be what you want...
on the side, if someone is looking for fetching the schema name from Spring JdbcTemplate (instead of plain JDBC), it would be jdbcTemplate.getDataSource().getConnection().getCatalog() for mySql
4
  • Either use SHOW DATABASES to see if it is inside,
  • Check the INFORMATION_SCHEMA,
  • or just do USE DATABASE; and catch the error.

Comments

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.