Javaで複数のデータベースをクエリする方法は何ですか?
Javaでは、複数のデータベースインスタンスにJDBCを使用して接続することで、クロスデータベースクエリを実行することができます。以下は、Javaでクロスデータベースクエリを行う方法を示した簡単なサンプルコードです。
import java.sql.*;
public class CrossDatabaseQuery {
public static void main(String[] args) {
String url1 = “jdbc:mysql://localhost:3306/database1”;
String url2 = “jdbc:mysql://localhost:3306/database2”;
String username = “root”;
String password = “password”;
try (Connection conn1 = DriverManager.getConnection(url1, username, password);
Connection conn2 = DriverManager.getConnection(url2, username, password)) {
// 在数据库1中执行查询
Statement stmt1 = conn1.createStatement();
ResultSet rs1 = stmt1.executeQuery(“SELECT * FROM table1”);
while (rs1.next()) {
// 处理结果集
}
// 在数据库2中执行查询
Statement stmt2 = conn2.createStatement();
ResultSet rs2 = stmt2.executeQuery(“SELECT * FROM table2”);
while (rs2.next()) {
// 处理结果集
}
} catch (SQLException e) {
e.printStackTrace();
}
} }
上記のコードは、異なる2つのデータベース接続conn1とconn2を使用してクエリを実行します。必要に応じて接続文字列、ユーザー名とパスワード、およびクエリを変更することができます。