Paullo
Paullo

Reputation: 2127

Get the connected mysql database name (JDBC)

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

Upvotes: 10

Views: 32167

Answers (4)

S Krishna
S Krishna

Reputation: 1333

Run

System.out.println(connection.getMetaData().getURL());
  • Paste the output in notepad
  • search the value for 'databaseName=yourDBName'

Upvotes: 0

Gord Thompson
Gord Thompson

Reputation: 123849

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

Upvotes: 22

SMA
SMA

Reputation: 37093

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

Upvotes: 1

Konstantin V. Salikhov
Konstantin V. Salikhov

Reputation: 4653

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.

Upvotes: 2

Related Questions