生成一段用java同步oracle,mysql数据的代码
时间: 2023-04-04 21:01:26 浏览: 187
java连接oracle和mysql数据库的jar包
你好,以下是一段用 Java 同步 Oracle 和 MySQL 数据的代码:
```
import java.sql.*;
public class SyncData {
public static void main(String[] args) {
Connection oracleConn = null;
Connection mysqlConn = null;
Statement oracleStmt = null;
Statement mysqlStmt = null;
ResultSet oracleRs = null;
ResultSet mysqlRs = null;
try {
// 连接 Oracle 数据库
Class.forName("oracle.jdbc.driver.OracleDriver");
oracleConn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "username", "password");
oracleStmt = oracleConn.createStatement();
oracleRs = oracleStmt.executeQuery("SELECT * FROM table_name");
// 连接 MySQL 数据库
Class.forName("com.mysql.jdbc.Driver");
mysqlConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name", "username", "password");
mysqlStmt = mysqlConn.createStatement();
// 同步数据
while (oracleRs.next()) {
int id = oracleRs.getInt("id");
String name = oracleRs.getString("name");
int age = oracleRs.getInt("age");
String sql = "INSERT INTO table_name (id, name, age) VALUES (" + id + ", '" + name + "', " + age + ")";
mysqlStmt.executeUpdate(sql);
}
System.out.println("数据同步完成!");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (oracleRs != null) oracleRs.close();
if (oracleStmt != null) oracleStmt.close();
if (oracleConn != null) oracleConn.close();
if (mysqlRs != null) mysqlRs.close();
if (mysqlStmt != null) mysqlStmt.close();
if (mysqlConn != null) mysqlConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
阅读全文