2016-02-22 146 views
1

我想执行2个查询。Mysql 2插入查询

第一个应该插入数据(特别是“产品”)或更新,以防数据库已经有这样的标题行。

第二个要插入新类别产品,插入\从第一次查询更新,并忽略任何插入,如果表中已经有这样的产品,这样的分类

这里是我的代码:

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()这意味着如果第一个查询只更新了数据,我将在第二个查询中使用不正确的行。

所以,我想知道如何同步这两个查询。

+0

叶氏,我只是忘了复制。 我不明白什么是“取” “[看这个问题的细节]”只是一个字符串,它不是一个链接 – quento

+0

(对不起 - 忘了粘贴链接)从你的第一个查询中取出last_insert_id,如果它存在,只执行第二个查询。 [请参阅此问题的详细信息](http://stackoverflow.com/questions/5513180/java-preparedstatement-retrieving-last-inserted-id) – Kenney

+0

您能提供一个示例吗? – quento

回答

1

由于您无权在第二个查询中访问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(); 

如果第一次查询没有导致INSERT,则没有足够的信息给产品添加到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 = ?), ?) 
+0

谢谢,我已经提供了这个解决方案!) – quento