Skip to main content

Posts

Showing posts from November, 2013

Connecting to MySQL with Java

I wanted to go over Database connections with Java, as it is something I've seen come up quite a bit, and it's really quite easy.  My intent is to actually go into detail on what actually happens here, so if all you're interested in is some boiler-plate code to get yourself connected, feel free to stop with the code listed below.  The only things to bear in mind are that I am using Java7 SE syntax for the catch block, and also that this method is tailored for the return of a single line result from the database.  Replace the if with a while loop ( and associated extra code ) if you want to loop through more than a single record The following method is called supplying an SQL statement as a string, i.e.:  SQLSingleQueryDB("SELECT * FROM products LIMIT 1");  The result is returned as a String: private String SQLSingleQueryDB( String query ) { String result = null; try { Class.forName("com.mysql.jdbc.Driver").