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
Show MySQL Databases The most common way to get a list of the MySQL databases is by using the mysql client to connect to the MySQL server and run the SHOW DATABASES command. If you haven't set a password for your MySQL user you can omit the -p switch.
jdbc. Driver. Connection URL: The connection URL for the mysql database is jdbc:mysql://localhost:3306/sonoo where jdbc is the API, mysql is the database, localhost is the server name on which mysql is running, we may also use IP address, 3306 is the port number and sonoo is the database name.
A database connection URL is a string that your DBMS JDBC driver uses to connect to a database. It can contain information such as where to search for the database, the name of the database to connect to, and configuration properties. The exact syntax of a database connection URL is specified by your DBMS.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With