Check if value exists in MySQL DB in Java?

12,673

I'd do this check in the where clause and use the Java side to simply check if this query returned any results:

Connection con = DatabaseConnection.getConnection();
PreparedStatement ps = 
    con.prepareStatement
    ("SELECT questid FROM completedQuests WHERE characterid = ? AND questid = ?");
ps.setInt (1, characterId);
ps.setInt (2, questId);
ResultSet rs = ps.executeQuery();

if (rs.next()) {
    // Quest already completed
} else {
    // Quest not completed yet
}

// Close resources etc.
Share:
12,673
Jacob Macallan
Author by

Jacob Macallan

Updated on June 09, 2022

Comments

  • Jacob Macallan
    Jacob Macallan almost 2 years

    I'm creating a game right now that stores quest values into a DB when a player completes his or her quest. The issue I'm having right now is writing a method that searches the MySQL table for the player id and the quest id to check if he or she has already completed it.

    I'm new to database programming in Java, so this was as far as I got by looking at some sample code elsewhere.

    public boolean checkQuest(int questid) {
       Connection con = DatabaseConnection.getConnection();
       PreparedStatement ps = con.prepareStatement("SELECT questid FROM completedQuests WHERE characterid = ?");
       ps.setInt(1, scriptId);
       ResultSet rs = ps.executeQuery();
    

    }

    Basically, I want to check if the quest id exists in the table. If it doesn't, that means the player has yet to complete the quest and thus it is available.