Friday, 23. September 2016
JDBC: Don't Forget to Commit
javatux, 23:31h
If you want to save something in a database with pure JDBC you would normally
The problem with this "forgotten" commit is, that no warning or exceptions comes up and you do not notice the lost data. This makes it hard to find the error - especially if the auto-commit is off only in same special cases.
This is the message you will see in this case. You only have to change the JDBC-URL and put ":proxy" after the jdbc prefix:
Happy Debugging...
- take a connection,
- create a statement with it,
- execute the statement and
- close the connection.
Connection connection = connectionProvider.getConnection();With this connection you can call a method which uses this connection to save e.g. an address:
private static void save(Address address, Connection connection) throws SQLException { PreparedStatement stmt = connection.prepareStatement( "INSERT INTO addressbook (email, name, " + "city) VALUES (?, ?, ?)"); try { stmt.setString(1, address.getEmail()); stmt.setString(2, address.getName()); stmt.setString(3, address.getCity()); int rc = stmt.executeUpdate(); if (rc < 1) { throw new SQLWarning("cannot save " + address); } } finally { stmt.close(); } }As last point you close the connection in the calling method:
connection.close();Does it work? In most cases yes, because normally the auto-commit flag is on, if you get a connection. But what happens, if auto-commit is off?
Auto-Commit Off = Lost Data
If auto-commit for a connecion is off you must call excplicit the commit:connection.commit();If you don't do it your changes are lost (there are some exeptions from that rule - the Oracle DB does a commit before it closes the connection).
The problem with this "forgotten" commit is, that no warning or exceptions comes up and you do not notice the lost data. This makes it hard to find the error - especially if the auto-commit is off only in same special cases.
The PatternTesting Proxy-Driver
PatternTesting provides you a wrapper around the original driver which allows you to log SQL statements but which warns you also if you forgot the commit statement for a connection with auto-commit off:1 entries were updated with 'INSERT INTO addressbook (email, name, city) VALUES ('ob@aosd.de', 'Oli B.', 'nowhere')' but not committed.
This is the message you will see in this case. You only have to change the JDBC-URL and put ":proxy" after the jdbc prefix:
DriverManager.getConnection("jdbc:proxy:hsqldb:mem:testdb")This is the URL for an HSQL memory DB. For more information see the Wiki article about SQL Logging and Monitoring.
Happy Debugging...
... comment