Biscuit128 Biscuit128 - 1 year ago 182
Java Question

MySQL upsert (ON DUPLICATE KEY) using JDBC Prepared Statement

I am trying to write a method to have an UPSERT functionality with a prepared statement in java. The code looks as follows;

public boolean addUserDeviceToken(String userid, String password, String deviceToken, Connection connection) {
String addDeviceToken = "INSERT INTO swiped.Users (userid, password, deviceToken) VALUES( ?, ?, ?) ON DUPLICATE KEY UPDATE devicetoken = ?";
boolean result = false;

ResultSet rs = null;
PreparedStatement st = null;
try {
st = connection.prepareStatement(addDeviceToken);
st.setString(1, userid);
st.setString(2, password);
st.setString(3, deviceToken);
st.setString(4, deviceToken);

What I am unsure of is whether i use
as surely it depends on the condition of the duplicate key?

What is the correct approach


Answer Source

You don't want to get a resultSet, there's no result apart the number of insertions or updates, simply use executeUpdate.

Extract from the javadoc :

Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement