Get the connected mysql database name (JDBC)

2020-08-26 04:11发布

问题:

How can get the name of the database name from connection object

try {
    this.ds = (DataSource) new InitialContext().lookup("java:comp/env/jdbc/amger");
} catch (NamingException ne) {
}
Connection conObj = ds.getConnection();

How do I get that Database name from con

回答1:

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


回答2:

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.



回答3:

Let's assume you used url as "jdbc:mysql://localhost/test"

Then do the following:

DatabaseMetaData dmd = connection.getMetaData();
String url = dmd.getURL();
System.out.println(url.substring(url.lastIndexOf("/") + 1));


标签: java mysql jdbc