Last active
August 29, 2015 14:03
-
-
Save georgewfraser/4de73d8f03c864665235 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package userdb; | |
import com.mchange.v2.c3p0.ComboPooledDataSource; | |
import org.junit.Test; | |
import java.beans.PropertyVetoException; | |
import java.sql.*; | |
import static org.junit.Assert.assertEquals; | |
public class Bugs { | |
public static final String SELECT_1 = "SELECT 1 AS value"; | |
// This test succeeds because there is no statement pooling | |
@Test | |
public void withoutStatementPooling() throws PropertyVetoException, SQLException { | |
ComboPooledDataSource db = new ComboPooledDataSource(); | |
db.setDriverClass("org.postgresql.Driver"); | |
db.setJdbcUrl("jdbc:postgresql://localhost/testdb"); | |
try (Connection connection = db.getConnection()) { | |
assertEquals(1, getOne(connection)); | |
assertEquals("value", getName(connection)); | |
} | |
} | |
// This test fails because it re-uses the same PreparedStatement | |
@Test | |
public void withStatementPooling() throws PropertyVetoException, SQLException { | |
ComboPooledDataSource db = new ComboPooledDataSource(); | |
db.setDriverClass("org.postgresql.Driver"); | |
db.setMaxStatementsPerConnection(100); // THIS LINE IS CRITICAL | |
db.setJdbcUrl("jdbc:postgresql://localhost/testdb"); | |
try (Connection connection = db.getConnection()) { | |
assertEquals(1, getOne(connection)); | |
assertEquals("value", getName(connection)); | |
} | |
} | |
private int getOne(Connection connection) throws SQLException { | |
PreparedStatement statement = connection.prepareStatement(SELECT_1); | |
ResultSet resultSet = statement.executeQuery(); | |
resultSet.next(); | |
int value = resultSet.getInt(1); | |
statement.close(); | |
return value; | |
} | |
private String getName(Connection connection) throws SQLException { | |
PreparedStatement statement = connection.prepareStatement(SELECT_1); | |
ResultSetMetaData metaData = statement.getMetaData(); | |
String name = metaData.getColumnName(1); | |
statement.close(); | |
return name; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment