但是,正如Konstantin在下面的评论中指出的那样,如果通过发出USE dbname语句更改当前的MySQL数据库,则该值不会更改. getCatalog()在的应用程序中可能仍然有用不更改数据库,或者通过使用setCatalog()更改当前数据库来执行"JDBC方式"但是对于MySQL而言,使用SELECT DATABASE()似乎总体上更安全.还请注意,getCatalog()与实际当前数据库之间的这种潜在差异取决于特定JDBC驱动程序的行为.出于好奇,我尝试使用适用于SQL Server的Microsoft JDBC驱动程序4.0进行类似操作,并且.getCatalog()实际上确实在运行USE dbname语句后立即意识到对当前数据库的更改.即是代码 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);} 产生了以下结果: getCatalog() returns: myDb Executing: USE mastergetCatalog() returns: master How can get the name of the database name from connection objecttry { 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 thatdoes not change databases, ordoes 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 codeString 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 mastergetCatalog() returns: master 这篇关于获取连接的mysql数据库名称(JDBC)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-04 07:16
查看更多