生成一段java代码,根据一个表名映射和一个字段映射,从oracle数据库向mysql同步增删改数据
时间: 2023-04-10 22:02:08 浏览: 215
java代码-使用java在Maven下用Spring+mysql 实现增删查改的源代码
好的,以下是一段Java代码,可以根据给定的表名映射和字段映射,从Oracle数据库向MySQL同步增删改数据:
```
import java.sql.*;
public class OracleToMySQLSync {
public static void main(String[] args) {
String oracleUrl = "jdbc:oracle:thin:@localhost:1521:orcl";
String oracleUser = "username";
String oraclePassword = "password";
String mysqlUrl = "jdbc:mysql://localhost:3306/dbname";
String mysqlUser = "username";
String mysqlPassword = "password";
String tableName = "table_name";
String[] fieldMap = {"field1", "field2", "field3"};
try {
// Connect to Oracle database
Connection oracleConn = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
Statement oracleStmt = oracleConn.createStatement();
// Connect to MySQL database
Connection mysqlConn = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
Statement mysqlStmt = mysqlConn.createStatement();
// Sync data from Oracle to MySQL
String selectSql = "SELECT * FROM " + tableName;
ResultSet rs = oracleStmt.executeQuery(selectSql);
while (rs.next()) {
String insertSql = "INSERT INTO " + tableName + " (";
String valuesSql = "VALUES (";
for (String field : fieldMap) {
insertSql += field + ",";
valuesSql += "'" + rs.getString(field) + "',";
}
insertSql = insertSql.substring(0, insertSql.length() - 1) + ")";
valuesSql = valuesSql.substring(0, valuesSql.length() - 1) + ")";
mysqlStmt.executeUpdate(insertSql + " " + valuesSql);
}
// Close connections
rs.close();
oracleStmt.close();
oracleConn.close();
mysqlStmt.close();
mysqlConn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
请注意,这只是一个简单的示例代码,实际应用中可能需要更多的错误处理和优化。
阅读全文