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
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 thatsetCatalog()
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 aUSE dbname
statement. That is, the codeproduced the following results:
Let's assume you used url as "jdbc:mysql://localhost/test"
Then do the following:
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.