Re: A JDBC bug or problem relating to string length in Java

From: Michael Stephenson <mstephenson(at)tirin(dot)openworld(dot)co(dot)uk>
To: palehaole(at)yahoo(dot)com
Cc: pgsql-jdbc(at)postgresql(dot)org
Subject: Re: A JDBC bug or problem relating to string length in Java
Date: 2003-09-02 09:22:37
Message-ID: Pine.LNX.4.44.0309020849290.5549-100000@tirin.openworld.co.uk
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-jdbc

joe user wrote:
> That's a good idea, but unfortunately
> Connection.close() throws SQLException, so I would
> have to do something like this:
>
> try { }
> catch { }
> finally {
> try { db.close(); }
> catch(SQLException e) { log(...); }
> }

I haven't been reading this thread at all, but you can avoid writing some
of the boiler plate code, with something similar to the following:

PreparedStatement ps = null;
try {
ps = prepareStatement(SQL_QUERY);
...
} catch (SQLException e) {
...
} finally {
closeStatement(ps);
}

// the next two methods can go in a superclass for all your DAO's

void prepareStatement(String query) throws SQLException {
Connection c = null;
try {
c = ...; // Get from pool or whatever
return c.prepareStatement(query);
} catch (SQLException e) {
// Since nobody has a reference to the statement, kill the
// underlying connection
if (c != null) {
c.close();// If this throws an SQLException, you'll lose e,
// you probably want to log it
}
throw e;
}
}

void closeStatement(PreparedStatement ps) {
if (ps == null) return;
Connection c = null;
try {
c = ps.getConnection();
ps.close();
} catch (SQLException e) {
...
} finally {
try {
if (c != null) {
c.close();
}
} catch (SQLException e) {
...
}
}
}

I've just written this off the top of my head, so it may not be quite
right, hopefully it's clear enough to get the general idea.

Michael
--
Web Applications Developer
Open World Ltd, 11 Riverside Court, Riverside Road, Bath, BA2 3DZ.
Tel: +44 1225 444950 Fax: +44 1225 336738 http://www.openworld.co.uk/

CONFIDENTIALITY NOTICE
The information contained in this message is confidential, intended only for
the use of the individual or the entity named as recipient. If the reader of
this message is not that recipient, you are notified that any
dissemination,
distribution or copy of this message is strictly prohibited. If you have
received this message in error, please immediately notify us by telephone on
the number above. Your co-operation is appreciated.

Browse pgsql-jdbc by date

  From Date Subject
Next Message Joseph Shraibman 2003-09-02 18:05:15 Why is JDBC so slow?
Previous Message joe user 2003-09-02 03:28:36 Test case (re: A JDBC bug or problem relating to string length in Java)