Search code examples
javasqlitesqlexceptiontry-catch-finally

Is that the best way to release SQLite connection in Java?


I need a good way to close SQLIte connections in Java. After a few suggestion by other users I decided to add to my code a finally block to be sure that closing operation are always executed.

public static boolean executeQuery(String query)
{

    Connection conn = null;
    Statement stmt = null;

    try
    {
        Class.forName("org.sqlite.JDBC");
        conn = DriverManager.getConnection(Global.dbPath);
        stmt = conn.createStatement();
        stmt.execute(query);
        return true;   
    }
    catch(ClassNotFoundException e)
    {
        System.out.println(e);
        return false;
    }
    catch(SQLException e)
    {
        System.out.println(e);
        return false;
    }
    finally
    {
        try 
        { 
            stmt.close();
            conn.close();
            return true;
        } 
        catch (SQLException ex) 
        {
            System.out.println ("Errore closing connections");
            return false;
        }
    }
}

I'm not sure that this is the best solution.

How can I optimize this for readability?


Solution

  • A few comments; nutshells:

    • Separate the SQL exceptions from the reflection exception.
    • Are your SQL exceptions recoverable? If not, throw an app-specific RuntimeException.
    • Wrap up the connection and statement close exceptions in a utility method, yours or a 3rd party's.
    • Don't short-change exception handling; dump the stack trace.

    This leads to the following:

    public static boolean executeQuery(String query) {
        try {
            Class.forName("org.sqlite.JDBC");
        } catch (ClassNotFoundException e) {
            throw new DbException("Could not find JDBC driver", e);
        }
    
        Connection conn = null;
        Statement stmt = null;
    
        try {
            conn = DriverManager.getConnection(Global.dbPath);
            stmt = conn.createStatement();
            stmt.execute(query);
            return true;
        } catch(SQLException e) {
            throw new DbException("Exception during statement execution", e);
        } finally {
            DbUtils.closeQuietly(conn);
            DbUtils.closeQuietly(stmt);
        }
    }
    

    (I'm using Apache Commons' DbUtils for its closeQuietly, it checks for null (yours didn't). Your own version might throw an app-specific exception as I do here with DbException. This wraps up all your DB-related exceptions into a single exception class, which may or may not be what you need.