nunya
nunya

Reputation: 315

How do I insert a database row if it does not exist?

I'm trying to insert some player data if it doesn't exist already but my statement creates a new row every time. This is the method I've written:

public void insertPlayerData(PlayerJoinEvent event) {
    Player player = event.getPlayer();
    UUID uuid = player.getUniqueId();
    String ign = player.getDisplayName();
    String profile = "1";

    try {
        //Connect To Database
        Connection con = getConnection();
        //Prepare Query Statement
        PreparedStatement posted = con.prepareStatement(
                "INSERT INTO players (uuid, ign, profile)"
                + "VALUES ('"+uuid+"', '"+ign+"', '"+profile+"')"
                + "ON DUPLICATE KEY UPDATE profile = '"+profile+"'");
        //Execute Statement
        posted.executeUpdate();
    } catch (Exception e) {
        System.out.println(lb + "Error: " +e);
    } finally {
        System.out.println(lb + "Player Data Inserted");
    }
}

Unfortunately my statement is creating duplicate rows. I've tried many different ways but came up short. Any ideas? Thanks ahead of time.

Upvotes: 0

Views: 600

Answers (1)

SKY
SKY

Reputation: 240

Your query says on duplicate key update profile = profile, which means you need to have profile as a unique key constraint while creating the table.

Upvotes: 1

Related Questions