Sunday, August 28, 2011
import java.sql
import java.sql.*;
public class DataTransfer {
private static String[] tableNames = new String[]{"SOME_TABLE_NAME"};
private static final int FETCH_SIZE = 100;
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Connection sourceConnection = ...;
Connection targetConnection = ...);
// records transfered counter
int c = 0;
for (String tableName : tableNames) {
final PreparedStatement ps = sourceConnection.prepareStatement("SELECT * FROM " + tableName);
ps.setFetchSize(FETCH_SIZE);
final ResultSet rs = ps.executeQuery();
final ResultSetMetaData metaData = rs.getMetaData();
final int columnCount = metaData.getColumnCount();
String insertSQL = "INSERT INTO " + tableName + " ";
while (rs.next()) {
StringBuffer columns = new StringBuffer("(");
StringBuffer params = new StringBuffer("(");
for (int i = 0; i < columnCount; i++) { columns.append(metaData.getColumnName(i+1)); params.append("?"); if ((i+1) != columnCount) { columns.append(","); params.append(","); } } columns.append(")"); params.append(")"); final String sql = insertSQL + columns.toString() + " VALUES " + params.toString(); c++; if (c > 0 && c % FETCH_SIZE == 0) {
System.out.println("Transfered " + c + " records.");
}
final PreparedStatement insertStatement = targetConnection.prepareStatement(sql);
for (int i = 0; i < columnCount; i++) {
insertStatement.setObject(i+1, rs.getObject(i+1));
}
insertStatement.execute();
targetConnection.commit();
insertStatement.close();
}
rs.close();
ps.close();
}
sourceConnection.close();
targetConnection.close();
System.out.println("Total transfered " + c + " records.");
}
}
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment