如果不存在则插入mysql条目,如果它存在java则更新

时间:2013-11-30 16:31:20

标签: java mysql

我想插入一个条目,如果它不存在,否则更新条目,我无法使用ON DUPLICATE KEY UPDATE,我对语法感到困惑。所以我试着做这样的事情:

    final String QUERY = "REPLACE INTO skills SET VALUES (" + insert(player) + ") WHERE playername = '" + player.getUsername() + "'";
    statement.execute(QUERY);

    statement.close();
    connection.close();
}

private static String insert(Player player) {
    String stringToReturn = "'" + player.getUsername() + "',";
    for (int index = 0; index < 25; index++) {
        stringToReturn += player.getSkills().getLevels()[index] + "," + ((int) player.getSkills().getXp()[index]) + ",";
    }
    stringToReturn = stringToReturn.substring(0, stringToReturn.length() - 1);
    return stringToReturn;
}

但那是不正确的语法,所以我想知道如何做到这一点?

playername是主键

1 个答案:

答案 0 :(得分:1)

我认为使ON DUPLICATE KEY UPDATE正常工作的正确语法是:

"INSERT INTO skills (playerName, otherColumn) 
    VALUES ('" + player.getUsername() + "', '" + insert(player) +"')
 ON DUPLICATE KEY UPDATE otherColumn = VALUES(otherColumn)";