java Oracle的表和mysql的表进行关联
时间: 2024-02-24 22:58:09 浏览: 166
java与mysql的连接数据库
在Java中,使用JDBC连接Oracle和MySQL数据库并进行表关联非常类似。以下是一些示例代码:
1. 假设我们有一个Oracle表(order),和一个MySQL表(product),我们想要通过订单中的产品ID关联这两个表,并查询每个订单的产品名称和价格。可以使用如下的代码:
```
String oracleUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
String oracleUser = "username";
String oraclePassword = "password";
String mysqlUrl = "jdbc:mysql://localhost:3306/database";
String mysqlUser = "username";
String mysqlPassword = "password";
Connection oracleConn = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
Connection mysqlConn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
Statement stmt = oracleConn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT order.product_id, product.name, product.price FROM order, product WHERE order.product_id = product.id");
while (rs.next()) {
String productName = rs.getString("name");
double productPrice = rs.getDouble("price");
// do something with the product name and price
}
rs.close();
stmt.close();
oracleConn.close();
mysqlConn.close();
```
这将使用JDBC连接Oracle和MySQL数据库,然后执行一个SELECT语句来关联订单表和产品表,并查询每个订单的产品名称和价格。
2. 如果我们需要在Java中进行更复杂的表关联操作,可以使用JOIN语句。例如,假设我们有一个Oracle表(order),和一个MySQL表(product),以及一个MySQL表(category),我们想要通过订单中的产品ID关联这三个表,并查询每个订单的产品名称、价格和类别名称。可以使用如下的代码:
```
String oracleUrl = "jdbc:oracle:thin:@localhost:1521:ORCL";
String oracleUser = "username";
String oraclePassword = "password";
String mysqlUrl = "jdbc:mysql://localhost:3306/database";
String mysqlUser = "username";
String mysqlPassword = "password";
Connection oracleConn = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
Connection mysqlConn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
Statement stmt = mysqlConn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT order.product_id, product.name, product.price, category.name FROM order JOIN product ON order.product_id = product.id JOIN category ON product.category_id = category.id");
while (rs.next()) {
String productName = rs.getString("name");
double productPrice = rs.getDouble("price");
String categoryName = rs.getString("category.name");
// do something with the product name, price, and category name
}
rs.close();
stmt.close();
oracleConn.close();
mysqlConn.close();
```
这将使用JDBC连接Oracle和MySQL数据库,然后执行一个JOIN语句来关联订单表、产品表和类别表,并查询每个订单的产品名称、价格和类别名称。
阅读全文