我正在尝试执行两个查询。
首先,应该插入数据(特别是“产品”)或更新,以防数据库已经有了带有此类标题的行。
第二种方法是为产品插入新的类别,从第一次查询中插入\更新的产品,如果表中已经有带有该类别的产品,则忽略任何插入。
这是我的代码:
conn = DatabaseConnection.getConnection();
stmt = conn.createStatement();
conn.setAutoCommit(false);
String updateSQL = "INSERT INTO product (title, price, `status`) " +
"VALUES(?, ?, ?)" +
"ON DUPLICATE KEY UPDATE price = ?, `status` = ?;"
PreparedStatement preparedStatement = conn.prepareStatement(updateSQL);
preparedStatement.setString(1, product.getTitle());
preparedStatement.setBigDecimal(2, product.getPrice());
preparedStatement.setInt(3, product.getStatus().ordinal());
preparedStatement.executeUpdate();
updateSQL = "INSERT IGNORE INTO product_categories (product_id, category_id) " +
"VALUES (last_insert_id(), ?);";
preparedStatement = conn.prepareStatement(updateSQL);
preparedStatement.setLong(1, categoryId);
preparedStatement.executeUpdate();
conn.commit();因此,问题是我使用了last_insert_id(),这意味着如果第一个查询刚刚更新了数据,我将在第二个查询中使用不正确的行。
因此,我想知道如何同步这两个查询。
发布于 2016-02-22 19:57:58
由于您在第二个查询中没有访问last_insert_id()的权限,所以必须获取as in the answers for this question。
下面是一个例子:
...
preparedStatement.executeUpdate(); // this is the first query
ResultSet rs = preparedStatement.getGeneratedKeys();
if ( rs.next() )
{
long last_insert_id = rs.getLong(1);
updateSQL = "INSERT IGNORE INTO product_categories (product_id, category_id) " +
"VALUES (?, ?);";
preparedStatement = conn.prepareStatement(updateSQL);
preparedStatement.setLong(1, last_insert_id);
preparedStatement.setLong(2, categoryId);
preparedStatement.executeUpdate();
}
conn.commit();如果第一个查询没有导致插入,那么就没有足够的信息将产品添加到product_category,在这种情况下,将跳过所有这些信息。这确实假定该产品已经属于这一类别。如果您对此不确定,并且希望无论如何执行第二个查询,则可以查询product_id:
SELECT id FROM product WHERE title = ?然后使用该id而不是last_insert_id变量,或者,您可以更改第二个查询并使用title作为键(尽管我坚持使用id):
INSERT IGNORE INTO product_categories (product_id, category_id)
VALUES (SELECT id FROM product WHERE title = ?), ?)https://stackoverflow.com/questions/35561754
复制相似问题