Reusing PreparedStatments

Hello,

Yet another question about PreparedStatments.

I have a application that processes events and (depending on conditions) save them into a database.

I have a Event class which represents the event.

class Event {

public int id;

public String name;

}

And a DataStore which handles the SQL part. Since it is alot of events ca 500/sec I thought that I should use PreparedStatments.

class DataStore {

private PreparedStatement pStmnt;

public DataStore(Connection conn) {

try {

pStmnt = conn.prepareStatement("INSERT INTO EVENTS VALUES(?, ?)");

} catch (SQLException e) {

e.printStackTrace();

}

}

public void storeEvent(Event e) throws SQLException {

pStmnt.clearParameters();

pStmnt.setInt(1, e.id);

pStmnt.setString(2, e.name);

pStmnt.executeUpdate();

}

public void closeDataStore() {

try {

pStmnt.close();

} catch (SQLException e) {

e.printStackTrace();

}

}

}

Then in the application I do something like this:

Event e;

while(appIsRunning) {

// Check the event and if all is good

dataStore.storeEvent(e);

}

dataStore.close();

The problem is when I start using this in multiple instances (processes/threads).

The INSERT creates a lock which isn't released until I close the PreparedStatment.

But closing and recreating the PreparedStatment. in DataStore#storeEvent(Event) seems to me to defeat the whole purpose of using a PreparedStatment ?

What have I missed ?

And in the main:

[1647 byte] By [pontus.ullgrena] at [2007-11-27 10:11:44]
# 1

You're reusing the same connection? Consider connection pooling.

BalusCa at 2007-7-28 15:15:32 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2

Well the problems with locks occur when I use multiple connection. Using only one connection all is fine.

Inside the application I only use one connection. At the moment is a single threaded application. I experience the locks when I start multiple applications (that is multiple connections) towards the same database.

My guess would be that using connection pooling with in a multi threaded application would produce the same error ?

pontus.ullgrena at 2007-7-28 15:15:32 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 3

How are you currently obtaining and storing the connection?

BalusCa at 2007-7-28 15:15:32 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 4

hmm ... I tried to make a small proof of concept application and then I didn't run into the same problem.

Guess I have to recheck the code in the actual program.

Thanks for the replies and sorry for waisting your time =/

pontus.ullgrena at 2007-7-28 15:15:32 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...