开发者

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.pre开发者_如何学运维pareStatement("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");
        }


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.
}


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.


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)


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!");
}


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... `

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜