简体   繁体   English

JDBC:查询结果并将批处理添加到另一个表中

[英]JDBC: Query results and add batch into another table

I have some mySQL tables: "books", "task" and "task_items". 我有一些mySQL表:“ books”,“ task”和“ task_items”。 I'm building an REST API (Java) that allow users to create tasks (basically edit fields) with some books. 我正在构建一个REST API(Java),允许用户使用一些书来创建任务(基本上是编辑字段)。 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. 当用户创建新任务时,我正在任务表中创建新行,获取最后的ID,选择一些书籍并将其全部添加到task_items表中。 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 表task_items

ID   TASK_ID   BOOK_ID   TITLE   AUTHOR
Empty at begining

When user access api/task/newtask, I'm doing something like this: 当用户访问api / task / newtask时,我正在执行以下操作:

// 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). 因此,我必须将SELECT查询中的resultSet批量插入task_items中,包括taskID(在所有行中都是commom)。 I dont't know how to do that (the TODO part). 我不知道该怎么做(TODO部分)。 I would be grateful for any help. 我将不胜感激。

I got it. 我知道了。 The "TODO" part should b like that: “ TODO”部分应像这样:

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

    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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