Biscuit128 Biscuit128 - 6 months ago 99
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
st.executeQuery();
or
st.executeUpdate();
as surely it depends on the condition of the duplicate key?

What is the correct approach

thanks

Answer

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