Multiple statement on a Connection
2 posts in topic
Flat View  Flat View

Posted By:   zhaohua_meng
Posted On:   Tuesday, December 11, 2001 12:29 AM

If I have a code snippet as following in a servlet, is the Statment thread safe? In other words, can I concurrently have more than one statement created on a single connection? What would happen to the Statements and the connection? Or I have to get a connection in the service() method for each Statement?


Connection conn=pool.getConnection();
service(req, res) {
Statement stmt=conn.createStatement();
String sql="select 1 from table_name";
ResultSet rs=stmt.executeQuery(sql);


Re: Multiple statement on a Connection

Posted By:   Anonymous  
Posted On:   Tuesday, January 1, 2002 08:22 PM

Unfortunately, this depends on the capabilities of the driver. A JDBC Compliant driver is required to be thread safe, but some poorly written drivers do so by forcing Statements to run serially, so you can appear to be hung and results are not as expected. And, of course, some drivers are just poorly written, period.

Re: Multiple statement on a Connection

Posted By:   Bozidar_Dangubic  
Posted On:   Tuesday, December 11, 2001 06:27 AM

you have to obtain a connection in the service method from the pool and not outside of the service method. a connection cannot have multiple statements open on it. this code above is not thread-safe. when client1 connects to the servlet and statement is created on the connection, if client2 connects before client1 finishes the execution (before connection is freed) SQLException will be thrown. so inside the service() method, get a connection from the pool, create a statement, execute a statement, close the statement, close the connection (return it to the pool). that would be a thread-safe way of doing it.
About | Sitemap | Contact