MySQL和DB2是常用的關系型數據庫管理系統。當需要從MySQL遷移數據至DB2時,需要進行以下步驟:
1.創建目標庫和表
CREATE DATABASE target_db; USE target_db; CREATE TABLE target_table ( column1 datatype(size), column2 datatype(size), column3 datatype(size), ... );
2.安裝DB2驅動程序和MySQL Connector/J
使用命令行安裝DB2 JDBC驅動程序,并將MySQL Connector/J放到classpath中。
3.編寫Java代碼遷移數據
import java.sql.*; public class MigrateData{ public static void main(String[] args) { Connection mysqlConn = null; PreparedStatement mysqlStmt = null; ResultSet mysqlRes = null; Connection db2Conn = null; PreparedStatement db2Stmt = null; try { //連接MySQL數據庫 mysqlConn = DriverManager.getConnection("jdbc:mysql://localhost:3306/source_db", "user", "password"); //查詢MySQL表 mysqlStmt = mysqlConn.prepareStatement("SELECT * FROM source_table"); mysqlRes = mysqlStmt.executeQuery(); //連接DB2數據庫 db2Conn = DriverManager.getConnection("jdbc:db2://localhost:50000/target_db", "user", "password"); //將數據插入DB2表 db2Stmt = db2Conn.prepareStatement("INSERT INTO target_table (column1, column2, column3, ...) VALUES (?, ?, ?, ...)"); while (mysqlRes.next()) { db2Stmt.setString(1, mysqlRes.getString("column1")); db2Stmt.setString(2, mysqlRes.getString("column2")); db2Stmt.setString(3, mysqlRes.getString("column3")); ... db2Stmt.executeUpdate(); } } catch (SQLException e) { e.printStackTrace(); } finally { //關閉連接和釋放資源 try { if (mysqlRes != null) mysqlRes.close(); if (mysqlStmt != null) mysqlStmt.close(); if (mysqlConn != null) mysqlConn.close(); if (db2Stmt != null) db2Stmt.close(); if (db2Conn != null) db2Conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
通過上述步驟,就可以將MySQL數據庫中的數據遷移至DB2。