user225269
user225269

Reputation: 10913

How to test if sql query returned true in java

I have this select query. How would I know if the query has found a match on the database?

try{
        PreparedStatement fetchPlayers = conn.prepareStatement("SELECT * FROM players WHERE P_Name='" + player + "'");
        fetchPlayers.executeQuery();



        }catch(Exception e){}

I tried doing this but it always returns true even if I input something that is not in the database.

if(fetchPlayers.execute()==true){
        System.out.println("True");
        }

Upvotes: 1

Views: 9467

Answers (5)

bw_üezi
bw_üezi

Reputation: 4564

PreparedStatement.execute() returns

true if the first result is a ResultSet object; false if the first result is an update count or there is no result

Use executeQuery() instead. What you're interested in is if the returned ResultSet has a positive count.

ResultSet rs = statement.executeQuery(query);
if ( rs.next() ) {
    // curser has moved to first result of the ResultSet 
    // thus here are matches with this query.
}

Upvotes: 6

BJH
BJH

Reputation: 11

A simple way to do this might be:

resultSet.last()
if (resultSet.getRow() < 1){
    // process case with no results
}else{
    // process case with results
    resultSet.beforeFirst();
}

Not sure about how fast this is, but if speed is no object... `

Upvotes: 0

veiset
veiset

Reputation: 2003

You could check how many columns that are returned, and from that see if its larger than 0:

ResultSet resultSet = statement.executeQuery(query);
ResultSetMetaData metaData = resultSet.getMetaData();
int columncount = metaData.getColumnCount();
if (columncount > 0) {
    System.out.println("Match found!");
}

Upvotes: 1

Paŭlo Ebermann
Paŭlo Ebermann

Reputation: 74750

First, you should not construct your statement by String concatenation, but use the placeholders and setXXX-methods.

executeQuery() returns a ResultSet, and this has some methods to iterate over the results. The next() method, for example, returns false if no more line is there.

Upvotes: 4

Brian Agnew
Brian Agnew

Reputation: 272217

From the doc:

Returns: true if the first result is a ResultSet object; false if it is an update count or there are no results

Your statement is returning a (albeit empty) ResultSet.

Have you tried using if exists ? Or at least getting the ResultSet and iterating through it, counting entries and determining if any entries exist (less efficient, but that may not be an issue).

(As Paŭlo has noted, you shouldn't concatenate SQL strings, since this leaves you open to SQL injection attacks. Rather you should use the parameter setting methods in the PreparedStatement object)

Upvotes: 1

Related Questions