在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();
????????}
????} }
上述代碼通過兩個不同的數據庫連接conn1
和conn2
分別執行查詢語句。你可以根據自己的需求修改連接字符串、用戶名和密碼,以及查詢語句。