Wednesday, November 16, 2011

Why Developers Shouldn't Be Using JDBC Connections, Statements and PreparedStatements

I cringe in pain every time I come across a project that's still using JDBC API interfaces / classes like Connection, Statement, PreparedStatement. Most of them are not legacy projects either.

I truly believe in this day and age you shouldn't be working directly with these low level interfaces and the associated boiler plate code you eventually end up writing. Basically you will have to get the connection, create statements or prepared statements, get the result set and once you are done close everything in a finally clause. This will not only create long, ugly and hard to read code but will make it very easy to introduce errors by say forgetting to close a connection.

So if you are not building a toy Java application you should really be using a high level API that automatically handles these tasks for you. I am not a very big fan of fancy ORM libraries and my preferred data access library has been Spring JDBC for the last two years or so. It gives you the full power of raw SQLs while making it easy do what you want to do with minimum coding. End result is simple, readable and most importantly maintainable and less error prone data access code.

Once you have configured Spring JDBC, an update or a select can be done in one line of code.



So if you are still using low level JDBC code in your applications, its time to consider moving to something like Spring JDBC. You can move your code gradually to the new APIs as Spring JDBC can and will coexist with low level JDBC code.

Take a look at the Spring documentation to get a more in depth idea of all available features of Spring JDBC

Don' forget to click the +1 button below if this post was helpful.

1 comment:

Frood said...

You forgot to mention, that the JDBC template can be used perfectly fine without the rest of Spring. Just pass a DataSource to the constructor and you're good to go.