Jacob Macallan
Jacob Macallan

Reputation: 979

Check if value exists in MySQL DB in Java?

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.

Upvotes: 3

Views: 15944

Answers (1)

Mureinik
Mureinik

Reputation: 312136

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.

Upvotes: 6

Related Questions