java中.sql的oracle语句导入到mysql
时间: 2023-07-12 12:42:39 浏览: 195
导入oracle数据库时的sql语句
可以使用Java中的JDBC来连接Oracle和MySQL数据库,然后通过执行SQL语句将Oracle中的数据导入到MySQL中。
下面是一个简单的Java代码示例,假设你已经准备好了Oracle和MySQL的JDBC驱动程序:
```java
import java.sql.*;
public class OracleToMySQL {
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/mysql";
String mysqlUser = "root";
String mysqlPassword = "password";
try {
// Connect to Oracle database
Connection oracleConnection = DriverManager.getConnection(oracleUrl, oracleUser, oraclePassword);
Statement oracleStatement = oracleConnection.createStatement();
// Connect to MySQL database
Connection mysqlConnection = DriverManager.getConnection(mysqlUrl, mysqlUser, mysqlPassword);
Statement mysqlStatement = mysqlConnection.createStatement();
// Export tables from Oracle to MySQL
String[] tableNames = { "table1", "table2", "table3" };
for (String tableName : tableNames) {
// Export table schema
ResultSet rs = oracleStatement.executeQuery("SELECT * FROM " + tableName + " WHERE 1=0");
ResultSetMetaData rsmd = rs.getMetaData();
int numColumns = rsmd.getColumnCount();
StringBuilder createTableSql = new StringBuilder("CREATE TABLE " + tableName + " (");
for (int i = 1; i <= numColumns; i++) {
String columnName = rsmd.getColumnName(i);
String columnType = rsmd.getColumnTypeName(i);
int columnSize = rsmd.getColumnDisplaySize(i);
createTableSql.append(columnName + " " + columnType + "(" + columnSize + "),");
}
createTableSql.setLength(createTableSql.length() - 1);
createTableSql.append(")");
mysqlStatement.execute(createTableSql.toString());
// Export table data
rs = oracleStatement.executeQuery("SELECT * FROM " + tableName);
while (rs.next()) {
StringBuilder insertSql = new StringBuilder("INSERT INTO " + tableName + " VALUES (");
for (int i = 1; i <= numColumns; i++) {
String value = rs.getString(i);
insertSql.append("'" + value + "',");
}
insertSql.setLength(insertSql.length() - 1);
insertSql.append(")");
mysqlStatement.execute(insertSql.toString());
}
}
// Close connections
mysqlStatement.close();
mysqlConnection.close();
oracleStatement.close();
oracleConnection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
需要注意的是,该代码仅供参考,实际应用中需要考虑更多的细节和异常情况。
阅读全文