使用jdbc我正在一个服务器上执行查询并获取resultSet1。现在,我根据resultSet1在另一台服务器上创建了一个表(服务器号:2)。在此之后,我想将ResultSet1直接插入到服务器2中创建的表中。做这个的最好方式是什么 ?就像我一样,是否有任何resultSet.insertRowInto()函数(不使用精确表数据的通用答案)?
Connection connection1, connection2;
connection1 = connectDB("192.168.40.1","db1","root","");
connection2 = connectDB("192.168.45.1","db2","root","");
//I have table1 in db1 and db2 and their structure is same
stmt = connection1.createStatement();
ResultSet = stmt.executeQuery("Select * from table1");
现在我还要求将resultSet复制到db2中的table1。
答案 0 :(得分:21)
public void copy(String table, Connection from, Connection to) throws SQLException {
try (PreparedStatement s1 = from.prepareStatement("select * from " + table);
ResultSet rs = s1.executeQuery()) {
ResultSetMetaData meta = rs.getMetaData();
List<String> columns = new ArrayList<>();
for (int i = 1; i <= meta.getColumnCount(); i++)
columns.add(meta.getColumnName(i));
try (PreparedStatement s2 = to.prepareStatement(
"INSERT INTO " + table + " ("
+ columns.stream().collect(Collectors.joining(", "))
+ ") VALUES ("
+ columns.stream().map(c -> "?").collect(Collectors.joining(", "))
+ ")"
)) {
while (rs.next()) {
for (int i = 1; i <= meta.getColumnCount(); i++)
s2.setObject(i, rs.getObject(i));
s2.addBatch();
}
s2.executeBatch();
}
}
}
然后不能使用columns.stream()
等和lambda表达式。这是创建INSERT
语句的另一种方法:
StringBuilder columnNames = new StringBuilder();
StringBuilder bindVariables = new StringBuilder();
for (int i = 1; i <= meta.getColumnCount(); i++)
if (i > 1) {
columnNames.append(", ");
bindVariables.append(", ");
}
columnNames.append(meta.getColumnName(i));
bindVariables.append('?');
}
String sql = "INSERT INTO " + table + " ("
+ columnNames
+ ") VALUES ("
+ bindVariables
+ ")"
我正在使用字符串连接来生成上面的SQL语句。要 非常 小心这项技术,以防止遇到SQL injection(和语法错误)! table
参数 绝不能 是用户输入!
setObject()
和getObject()
,而不是可能需要的更具体的类型。