简体   繁体   中英

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. 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.

item_id is the only column in the table.

I also want to delete test table data after I inserted them to the test_t table. 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.

        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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM