本文介绍了使用JDBC Prepared语句的MySQL upsert(ON DUPLICATE KEY)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Java中的准备好的语句编写一种具有UPSERT功能的方法.该代码如下所示;

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);

我不确定是使用st.executeQuery();还是st.executeUpdate();,这肯定取决于重复密钥的条件?

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?

什么是正确的方法

谢谢

推荐答案

您不想获得resultSet,除了插入或更新的数量之外没有结果,只需使用 executeUpdate .

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

从javadoc中提取:

Extract from the javadoc :

这篇关于使用JDBC Prepared语句的MySQL upsert(ON DUPLICATE KEY)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 06:50