Java PreparedStatement and ON DUPLICATE KEY UPDATE: how do I know whether row was inserted or updated?

前端 未结 2 1363
無奈伤痛
無奈伤痛 2021-01-05 12:50

Having following code, how do I know if the execute() method resulted in insert or in update?:

Connection c = DriverManager.getConnection(connectionString);
         


        
2条回答
  •  清酒与你
    2021-01-05 13:20

    Use executeUpdate instead as it returns an int row count.

    UPDATE 1: According to the MySQL INSERT ... ON DUPLICATE KEY UPDATE documentation:

    With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, and 2 if an existing row is updated.

    UPDATE 2: INSERT IGNORE may also be an option:

    INSERT IGNORE INTO `table`(`field1`) VALUES (?)
    

    executeUpdate should return 1 when a new row is inserted and 0 when there is a duplicate.

提交回复
热议问题