简体   繁体   中英

JDBC: Query results and add batch into another table

I have some mySQL tables: "books", "task" and "task_items". I'm building an REST API (Java) that allow users to create tasks (basically edit fields) with some books. When user creates a new task, I'm creating a new row in task table, getting the last ID, selecting some books and add all of it into task_items table. Something like this:

Table books:

ID   TITLE   AUTHOR
1    Book A  John
2    Book B  Doe

Table task

ID   NAME   DATE
Empty at begining

Table task_items

ID   TASK_ID   BOOK_ID   TITLE   AUTHOR
Empty at begining

When user access api/task/newtask, I'm doing something like this:

// Creating task and return it's ID, everything works well
conn.setAutoCommit(false);
query = conn.pareStatement(INSERT INTO task VALUES ("New task", NOW()), Statement.RETURN_GENERATED_KEYS);
query.execute();
ResultSet rs = query.getGeneratedKeys();
if (rs.next()) {
    taskId = rs.getInt(1);
}
else {
    conn.rollback();
    return false; // can't create task
}

// Selecting some (or all) books
query = conn.prepareStatement("SELECT * FROM books");
ResultSet rs = query.executeQuery();

if (!rs.isBeforeFirst()) {
    conn.rollback();
    return false; // no books
}

// There's some books, insert them into task_items with taskId
// TODO

return true;

So, I have to insert batch the resultSet from the SELECT query into task_items, including taskID (with is commom to all rows). I dont't know how to do that (the TODO part). I would be grateful for any help.

I got it. The "TODO" part should b like that:

// There's some books, insert them into task_items with taskId
rs = query.executeQuery();
query = conn
            .prepareStatement("INSERT INTO task_items"
                    + "(TASK_ID, BOOK_ID, TITLE, AUTHOR)"
                    + "VALUES"
                    + "(?, ?, ?, ?)");

    while (rs.next()) {
        query.setInt(1, taskId);
        query.setInt(2, rs.getInt("ID"));
        query.setString(3, rs.getString("TITLE"));
        query.setString(4, rs.getString("AUTHOR"));         

        query.addBatch();
    }

    System.out.println("executing batch...");

    query.executeBatch();

    System.out.println("batch executed");
    query.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