FindBug Problem: article.Rank.decreaseRank(String) may fail to close Statement

18 views
Skip to first unread message

Lishun(Jason) Wu

unread,
Dec 2, 2011, 1:17:22 AM12/2/11
to CPSC410-2011
Hi,
I am running into some problem with FindBug Problem where it ask
certain method that contain a sql statment will fail to close the
statement. I tried several options such as having a finally and close
connection there, but it seems nothing will fix this bug. I am out of
idea...
The code something like this:
public void increaseRank(String key) throws SQLException
{
Statement statement = connection.createStatement();
String query="SELECT rank From article Where articleKey='"+key+"';";
ResultSet resultSet=statement.executeQuery(query);
int rank = 0;
while(resultSet.next())
{
rank=resultSet.getInt("rank");
}
rank++;
System.out.println(rank);
query="UPDATE article SET rank='"+Integer.toString(rank)+"' WHERE
articleKey='"+key+"';";
statement.executeUpdate(query);
}

Thanks,
Jason

Eric Wohlstadter

unread,
Dec 2, 2011, 1:50:45 AM12/2/11
to cpsc41...@googlegroups.com
Hi Jason,
 If you try to close a resource and it throws an exception you need to "give up". It won't help to try and close it again. For example you could do this below, although this assumes you have a "catch-all" handler in your Servlet to deal with runtime exceptions. Also, your code looks like it might have an SQL Injection attack vector, if you are not careful.

           Statement statement = connection.createStatement();

try {
            String query="SELECT rank From article Where articleKey='"+key+"';";
            ResultSet resultSet=statement.executeQuery(query);
            int rank = 0;
            while(resultSet.next())
            {
                    rank=resultSet.getInt("rank");
            }
            rank++;
            System.out.println(rank);
            query="UPDATE article SET rank='"+Integer.toString(rank)+"' WHERE articleKey='"+key+"';";
            statement.executeUpdate(query);
} finally {
try {
statement.close();
} catch(Exception e) {
throw new RuntimeException(e);
Reply all
Reply to author
Forward
0 new messages