3

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.

2
  • Do you have a database already setup? Can you already connect to it? Commented Jun 16, 2015 at 6:26
  • I do have a database set up and connected to it. Commented Jun 16, 2015 at 6:27

1 Answer 1

6

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.
Sign up to request clarification or add additional context in comments.

9 Comments

What I originally intended was something of the sort where I pass a questid through a method parameter and check it to see if it exists in the DB. I don't think this does that comparison. My bad for unclarification. Or do I replace the ? with the parameter?
I fail to understand the question there. What is lacking from this solution?
If I was to search for a specific quest id, would I substitute the "?"s with the specific questid?
@Xari no - you would set the PreparedStatement with it. That's what ps.setInt (2, questId); takes care of.
@Xari The "?" isn't a placeholder for you to replace, it's the way JDBC's syntax allows you to parameterize PreparedStatements.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.