MySQL upsert (ON DUPLICATE KEY) using JDBC Prepare

2019-08-04 14:55发布

问题:

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

回答1:

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