[英]Copy one table data and insert those to another table in the same database using JAVA?
I want to select some data from one MYSQL database table and insert those selected data to another table in the same database using JAVA. 我想从一个MYSQL数据库表中选择一些数据,然后使用JAVA将那些选择的数据插入同一数据库中的另一个表中。 Both tables have the same structure. 这两个表具有相同的结构。 So far i can select data, but i cannot insert those data. 到目前为止,我可以选择数据,但不能插入这些数据。
test and test_t are the tables. test和test_t是表。
item_id is the only column in the table. item_id是表中的唯一列。
I also want to delete test table data after I inserted them to the test_t table. 在将测试表数据插入到test_t表中之后,我也想删除它们。 This test table is like a temporary table. 该测试表就像一个临时表。
This is my method. 这是我的方法。
private void testM() throws Exception {
pooler = DBPool_SF.getInstance();
dataSource = pooler.getDataSource();
Connection con = dataSource.getConnection();
con.setAutoCommit(false);
PreparedStatement ps,ps1 = null;
ResultSet rs = null;
String SEL_QUERY = "select item_id from test";
String UPDATE_QUERY = "insert into test_t values(?)";
ps = con.prepareStatement(SEL_QUERY);
rs = ps.executeQuery();
ps1 = con.prepareStatement(UPDATE_QUERY );
while (rs.next()) {
String id = rs.getString("item_id");
System.out.println(id);
ps1.setString(1,id);
ps1.addBatch();
}
ps1.executeBatch();
con.close();
}
Following code will work. 以下代码将起作用。 If you mention setAutoCommit(false), then you need commit at the end. 如果提到setAutoCommit(false),则需要在最后提交。
con.setAutoCommit(false);
PreparedStatement ps, ps1 = null;
ResultSet rs = null;
Statement st = null;
String SEL_QUERY = "select item_id from test";
String UPDATE_QUERY = "insert into test_t values(?)";
String DELETE_QUERY = "delete from test";
st = con.createStatement();
ps = con.prepareStatement(SEL_QUERY);
rs = ps.executeQuery();
ps1 = con.prepareStatement(UPDATE_QUERY);
while (rs.next())
{
String id = rs.getString("item_id");
System.out.println(" item_id : " + id);
ps1.setString(1, id);
ps1.addBatch();
}
ps1.executeBatch();
st.execute(DELETE_QUERY);
con.commit();
con.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.