Alex Benoit
Alex Benoit

Reputation: 21

How do I make JAVA perform an action based on MySQL data

I would like to make a java code that has different outcomes that are determined by data inside of a MySQL column. I have everything set up and I can connect to the database and view data. I don't know how I would use "If" with a mysql column. Here is my code: http://pastebin.com/UsJC7Qzx

What I'm trying to do specifically: I want to make the code print "Thanks for voting" if the MySQL column "given" is equal to 0 and then it will set the column to 1. And if the column is equal to 1 it will say "Thanks again for voting."

This is just a simple base for a voting reward system I'm doing for my video game.

If you don't have very good understanding of what I am trying to say read my notes inside of the code.

Upvotes: 0

Views: 78

Answers (2)

Kal
Kal

Reputation: 24910

I think you're almost there. Just need a couple of more lines.

st.executeQuery(give); returns a ResultSet. If you are guaranteed that your query will only return one result, you could simply do

ResultSet result = st.executeQuery(give);
if ( result.next() ) { // advances the resultset to the first result.
     int actualVal = given.getInt('given');
     if ( actualVal == 0 ) {
        System.out.println("Thanks for voting");
        // do the update here
        st.executeUpdate("update has_voted set given = 1 where ...........");
     }
     else
        System.out.println("Thanks again for voting");
}

Upvotes: 0

Reimeus
Reimeus

Reputation: 159754

It would look something like this:

while (given.next()) {
    if (given.getInt("given") > 0) {
        System.out.println("Thanks again for voting");
    } else {
        System.out.println("Thanks for voting");
    }
}

Would recommend that you rename the given resultset to something like say 'resultSet'.

Upvotes: 1

Related Questions