实现跨库抽取的java代码
时间: 2024-06-17 16:06:00 浏览: 4
跨库抽取是指从多个数据库中提取数据的过程。在Java中,你可以使用JDBC(Java Database Connectivity)来连接多个数据库并抽取数据。下面是一个简单的跨库抽取的Java代码示例:
```
import java.sql.*;
public class CrossDBExtraction {
public static void main(String[] args) {
Connection conn1 = null;
Connection conn2 = null;
Statement stmt1 = null;
Statement stmt2 = null;
ResultSet rs1 = null;
ResultSet rs2 = null;
try {
//连接第一个数据库
String dbURL1 = "jdbc:mysql://localhost:3306/db1";
String username1 = "user1";
String password1 = "pass1";
conn1 = DriverManager.getConnection(dbURL1, username1, password1);
stmt1 = conn1.createStatement();
//连接第二个数据库
String dbURL2 = "jdbc:mysql://localhost:3306/db2";
String username2 = "user2";
String password2 = "pass2";
conn2 = DriverManager.getConnection(dbURL2, username2, password2);
stmt2 = conn2.createStatement();
//从第一个数据库中选择数据
String sql1 = "SELECT * FROM table1";
rs1 = stmt1.executeQuery(sql1);
//从第二个数据库中选择数据
String sql2 = "SELECT * FROM table2";
rs2 = stmt2.executeQuery(sql2);
//处理第一个结果集
while (rs1.next()) {
//处理结果集中的每一行数据
//...
}
//处理第二个结果集
while (rs2.next()) {
//处理结果集中的每一行数据
//...
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
//关闭结果集、语句和连接
try {
if (rs1 != null) {
rs1.close();
}
if (rs2 != null) {
rs2.close();
}
if (stmt1 != null) {
stmt1.close();
}
if (stmt2 != null) {
stmt2.close();
}
if (conn1 != null) {
conn1.close();
}
if (conn2 != null) {
conn2.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
}
```
以上代码展示了如何连接两个不同的数据库,并从每个数据库中提取数据。你可以根据自己的需求修改这个代码,以便满足你的具体业务需求。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)