Get the connected mysql database name (JDBC)

If you know that DB is Mysql you could just perform SELECT DATABASE() on your connection and read the resulset with current database name in it.

Here is description of DATABASE function.


Probably the most straightforward way to get the database name from the JDBC Connection object itself is via the getCatalog() method:

Connection#getCatalog()

However, as Konstantin pointed out in his comment below, that value will not change if the current MySQL database is changed by issuing a USE dbname statement.

getCatalog() might still be useful in an application that

  • does not change databases, or
  • does things "The JDBC Way" by using setCatalog() to change the current database,

but for MySQL, using SELECT DATABASE() appears to be safer overall.

Note also that this potential discrepancy between getCatalog() and the actual current database depends on the behaviour of the particular JDBC driver. Out of curiosity I tried something similar with the Microsoft JDBC Driver 4.0 for SQL Server and .getCatalog() was indeed aware of the change to the current database immediately after running a USE dbname statement. That is, the code

String connectionUrl = "jdbc:sqlserver://localhost:52865;"
        + "databaseName=myDb;" + "integratedSecurity=true";
try (Connection con = DriverManager.getConnection(connectionUrl)) {
    System.out.println(String.format(
            "getCatalog() returns: %s", 
            con.getCatalog()));
    try (Statement s = con.createStatement()) {
        System.out.println("           Executing: USE master");
        s.execute("USE master");
    }
    System.out.println(String.format(
            "getCatalog() returns: %s", 
            con.getCatalog()));
} catch (Exception e) {
    e.printStackTrace(System.out);
}

produced the following results:

getCatalog() returns: myDb
           Executing: USE master
getCatalog() returns: master

Tags:

Mysql

Java

Jdbc