1

If I have a java code that deals with database and I want to use multi-threading in my application. Each thread suppose to run a function that contains insertion to the database. My question is: Where should I place the following statements:

Connection con = DriverManager.getConnection (dbUrl);
query = " insert into schema.table values (default,?,?)";   
preparedStmt = con.prepareStatement(query);

Should I place them in the run so every thread execute them? or in the Main so they are executed once only? or inside the function that is called by the run function ? I need to know the right method to insert to Database when I have multi-threads. Thanks.

Jury A
  • 19,192
  • 24
  • 69
  • 93

1 Answers1

2

You should consider creating a ConnectionPool and get connection from this pool for your database related work.

The following two links might be of interest to you:

Connection Pooling
Apache Commons DBCP

Edit Thanks to @MJB for pointing this one out:
c3p0 is another one that is pretty good.
BoneCP is another one

But at the end of the day, the simple point is this: You need to implement connection pooling. Which one you choose is totally your decision and based on your requirements.

Sujay
  • 6,753
  • 2
  • 30
  • 49
  • Connection pooling is probably the best way to deal with this. You might also consider passing messages to the thread that handles database interaction if the other threads do different kinds of jobs. – Joshua Martell Jul 07 '12 at 20:33