有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何使用JDBC在一台服务器上连接多个数据库?

我试图在一个运行的实例上访问多个数据库中的数据。这些数据库的表结构都是相同的;据我所知,使用jdbc创建新的连接非常昂贵。但是jdbc的连接字符串需要这样的格式 jdbc:mysql://hostname/ databaseName,它需要指定一个特定的数据库。 所以我想知道有没有办法用一个连接查询多个数据库中的数据

Multiple databases on a single running instance


共 (1) 个答案

  1. # 1 楼答案

    MySQL文档在这个主题上写得很糟糕

    ^{} Syntax页指的是^{} Syntax页,用于说明如何编写表名,即使不使用JOIN子句。^{} Syntax页面只是说tbl_name,没有进一步定义这是什么。底部甚至有一条评论指出:

    This page needs to make it explicit that a table reference can be of the form schema_name.tbl_name, and that joins between databases are therefore posible.

    Schema Object Names页面没有说明限定名称,但有一个子页面名为Identifier Qualifiers,它表示可以使用语法db_name.tbl_name.col_name引用表列。该页面没有提到使用^{引用的能力

    但是,如果您可以使用db_name.tbl_name.col_name引用,那么只有当您也可以使用db_name.tbl_name引用时才有意义,这意味着您可以使用单个Connection访问所有数据库,如果您不介意在SQL语句中限定表名的话


    正如@MarkRotteveel在评论中提到的,您还可以使用^{}方法切换数据库

    这在MySQL Connector/J 5.1 Developer Guide中有记录:

    Initial Database for Connection

    If the database is not specified, the connection is made with no default database. In this case, either call the setCatalog() method on the Connection instance, or fully specify table names using the database name (that is, SELECT dbname.tablename.colname FROM dbname.tablename...) in your SQL. Opening a connection without specifying the database to use is generally only useful when building tools that work with multiple databases, such as GUI database managers.

    Note: Always use the Connection.setCatalog() method to specify the desired database in JDBC applications, rather than the USE database statement.