Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 961
Ismail Marmoush Avatar asked Apr 15 '11 15:04

Ismail Marmoush


3 Answers

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") );
}
like image 105
bw_üezi Avatar answered Nov 07 '22 06:11

bw_üezi


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);
}
like image 25
Adi Sembiring Avatar answered Nov 07 '22 07:11

Adi Sembiring


  • Either use SHOW DATABASES to see if it is inside,
  • Check the INFORMATION_SCHEMA,
  • or just do USE DATABASE; and catch the error.
like image 20
Konerak Avatar answered Nov 07 '22 07:11

Konerak