Java Forum

Ask Question   UnAnswered
Home » Forum » Java       RSS Feeds

Static Initializer and JDBC

  Asked By: Alex    Date: Sep 18    Category: Java    Views: 598

I have a question about design that I am hoping somebody can help me out
with. I am creating a JDBC connection to a remote server. Somebody has
advised me to put the JDBC connect into a static initializer. Is that a
good idea? My concern is that how is this object going to handle net
errors, database errors, etc when the application is stating up since the
object will be instantiated before the rest of the application is even



3 Answers Found

Answer #1    Answered By: Mark R     Answered On: Sep 18

I used static  connections to make sure there is
only one connection  to the database  in the whole
application, shared between the client classes. But
never in a static initializer, I use instead a static
wrapper method to access it (getConnection() or
something), so this method takes the work of, in the
first call, make the connection, handle  connection
errors, etc and in the following calls to check if the
connection is still valid and make again the
connection if it's not alive.
Remember that static initializers are not executed
when the application  starts. They're executed when the
class is loaded. So if the class with the static
initializer is not used, it will not be loaded,
neither initialized. Therefore, your static
initializer will be executed in the first reference to
the class (somebody tell me if I'm wrong).

Answer #2    Answered By: Jaime Bowman     Answered On: Sep 18

another thing to consider:
some database  servers do not allow continuous connections - you'll have
to suss that one out.
if you can have continuous connections, perhaps use a lazy
initialisation that is run the first time a connection  is needed.

Answer #3    Answered By: Brandon Tucker     Answered On: Sep 18

I dont think there is any big advantage of using
static intializer block for connection  if you are
using it only once.It will give you Connection object
just before the application  is started which you can
use later in your code.
According to me if you are using the database  heavily
then you should consider using connection pool from
where you can get connection object  as and when
required.It also reduces the overhead of opening and
closing the connection everytime you are using it.

Didn't find what you were looking for? Find more on Static Initializer and JDBC Or get search suggestion and latest updates.