我想从数据库表A中获取数据并创建一个insert语句来加载表B. 为了保留数据类型,我使用ResultSet方法创建一个Time statament来从表A中读取,如下所示。
插入表值 (rs.getString(1),rs.getInt(3),rs.getString(5),rs.getInt(6),rs.getString(7),rs.getInt(8),rs.getString(9), rs.getInt(10),rs.getString(11),rs.getInt(13),rs.getString(16))
我的下一步是迭代表A中的记录并将这些插入语句作为BATCH发送到表B.但是如何在(rs.getString(1) and rs.getInt(3) ... )
上循环时用实际值替换字符串rs.next()
。
答案 0 :(得分:1)
您需要使用占位符为此插件创建PreparedStatement
:
PreparedStatement insert = connection.prepareStatement("INSERT INTO TABLE_B VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
while (rs.next()) {
insert.setString(1, rs.getString(1));
insert.setInt(2, rs.getInt(3));
insert.setString(3, rs.getString(5));
insert.setInt(4, rs.getInt(6));
insert.setString(5, rs.getString(7));
insert.setInt(6, rs.getInt(8));
insert.setString(7, rs.getString(9));
insert.setInt(8, rs.getInt(10));
insert.setString(9, rs.getString(11));
insert.setInt(10, rs.getInt(13));
insert.setString(11, rs.getString(16));
insert.addBatch();
// call insert.executeBatch() once you accumulate enough records for insert
}
如果目标表中的列类型与源表中使用的列类型匹配,则可以使用ResultSetMetaData
在PreparedStatement
中设置参数
ResultSetMetaData md = rs.getMetaData();
while (rs.next()) {
for (int m = 1; m <= md.getColumnCount(); m++) {
if (rs.getObject(m) == null) {
targetStatement.setNull(m, md.getColumnType(m));
} else if (md.getColumnType(m) == OracleTypes.VARCHAR) {
targetStatement.setString(m, rs.getString(m));
} else if (md.getColumnType(m) == OracleTypes.NUMBER) {
targetStatement.setDouble(m, rs.getDouble(m));
} else if (md.getColumnType(m) == OracleTypes.CHAR) {
targetStatement.setString(m, rs.getString(m));
} else if (md.getColumnType(m) == OracleTypes.TIMESTAMP) {
targetStatement.setTimestamp(m, rs.getTimestamp(m));
} else if (md.getColumnType(m) == OracleTypes.DATE) {
targetStatement.setDate(m, rs.getDate(m));
} else {
targetStatement.setString(m, rs.getString(m));
}
}
insert.addBatch();
// call insert.executeBatch() once you accumulate enough records for insert
}
答案 1 :(得分:1)
首先尝试在一个语句中完成所有操作。
INSERT INTO xtable (x1, x2, x3, x4, x5, x6, x7, x8, x9, x10, x11)
(SELECT y1, y3, y5, y6, y7, y8, y9, y10, y11, y13, y16
FROM ytable
WHERE ...)
否则请使用@Ivan的PreparedStatement。
答案 2 :(得分:0)
String template = "Insert into TABLE_B values(\"{0}\", {1}, \"{2}\", {3}, \"{4}\", {5}, \"{6}\", {7}, \"{8}\", {9}, \"{10}\")";
MessageFormat mf = new MessageFormat(template);
while (rs.next()}
Object[] params = new Object[11];
params[0] = rs.getString(1);
params[1] = rs.getInt(3);
params[2] = rs.getString(5);
params[3] = rs.getInt(6);
params[4] = rs.getString(7);
params[5] = rs.getInt(8);
params[6] = rs.getString(9);
params[7] = rs.getInt(10);
params[8] = rs.getString(11);
params[9] = rs.getInt(13);
params[10] = rs.getString(16);
String command = mf.format(params);
//do with command what ever want to do
}
当你可以使用一个SQL命令从表到表插入时,为什么要烦恼:INSERT INTO...SELECT