3

I'm trying write a test for a method that returns a java.sql.Connection to connect to a PostgreSQL.

My test is very straightforward:

@Test
public void connectionFactoryShouldReturnOpenConnection() throws Exception {
    Connection conn = ConnectionFactory.getConnection();

    assertTrue(conn.isValid(2));
}

The isValid call fails, though:

org.postgresql.util.PSQLException: Method org.postgresql.jdbc4.Jdbc4Connection.isValid(int) is not yet implemented.
at org.postgresql.Driver.notImplemented(Driver.java:753)
at org.postgresql.jdbc4.AbstractJdbc4Connection.isValid(AbstractJdbc4Connection.java:109)
at org.postgresql.jdbc4.Jdbc4Connection.isValid(Jdbc4Connection.java:21)

What's going on? Surely there is a PostgreSQL JDBC driver that implements the methods of Java 1.6 such as isValid()?

Here the details on the driver I'm using:

<groupId>postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.0-801.jdbc4</version>
2
  • I wonder if this is a case of: it didn't exist before 1.6, so all connection pool implementations support specifying a statement to execute to test the connection. Now since connection pools all support that, there isn't much demand for drivers that support the new method? Kind of perverse, but that's life. Commented Mar 11, 2011 at 23:28
  • 1
    @EricWilson - It appears that isValid() was implemented starting in version 9.2.1000 (released September 27, 2012) of the driver (I apologize for the double-notification) Commented May 1, 2013 at 22:50

2 Answers 2

4

Perform a simple query, if it works, it's valid. If not, it's not.

And by simple query I mean something like:

SELECT 1;

Really simple.

Sign up to request clarification or add additional context in comments.

3 Comments

If there is no other option, I'll go with that. But it doesn't make me confident in my driver to find such a simple method not implement.
bad idea, select 1 on a table with >2 mio rows becomes super slow... is there a way to disable this test connection thing at all?
you use just "select 1" without any table. And this will return "1". Very quick query.
2

From the postresql driver source code the AbstractJdbc4Connection.isValid() throws this exception when called:

public boolean isValid(int timeout) throws SQLException
{
    checkClosed();
    throw org.postgresql.Driver.notImplemented(this.getClass(), "isValid(int)");
}

1 Comment

That is interesting, and confirms my experience, but doesn't answer the question of how a connection can be best verified using Java JDBC and Postgres.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.