Skip to main content

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").newInstance();
              Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/specific_database", "root", "");
              Statement stmt = (Statement)con.createStatement();
              ResultSet rs = stmt.executeQuery(query);
            
              if ( rs.next() ) result = rs.getString("modelLine");
              
        } catch ( SQLException | ClassNotFoundException | InstantiationException | IllegalAccessException e ) {
              JOptionPane.showMessageDialog( this, e.getMessage() );
        }
        return result;
    }

Now, let's pick apart the different statements, and see what they do

Class.forName("com.mysql.jdbc.Driver").newInstance();

Both of these methods are found under java.lang.Class, which is a subclass of java.lang.Object.

forName("com.mysql.jdbc.Driver")
Returns the Class Object associated with the class or interface with the given string name. So, in this case, the Class Object of "com.mysql.jdbc.Driver" is returned. Upon this returned class object, we're calling:
newInstance()
Which creates a new instance of the class represented by the class object on which it's called ( here, Driver ).  So, in short, we're basically instantiating the Driver of java.sql.* that is associated with MySQL.

So, we've essentially got our MySQL Driver set up, now we need a connection to our MySQL Database, which is handled by Connection, and the DriverManager class ( both members of java.sql ).  So in the next line:
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/specific_database", "root", "");
we are creating a variable of type Connection, and initializing it from our previously instantiated Driver through the DriverManager. It breaks down like this:

Connection is an Interface ( of java.sql ) that handles a connection (session) with a specific database. All our SQL statements that are executed, and the results that are returned, happen within the context of a connection. We initialize our connection by giving it a connection obtained through whatever database Driver we are using for our particular database. In this case, it's MySQL. The DriverManager handles whatever drivers we happen to have loaded, by selecting an appropriate driver from the set of registered JDBC drivers. DriverManager has a method,
getConnection( String url, String user, String password) throws SQLException
that attempts to establish a connection to the given database URL.  So, we feed it the connection url to our database, "jdbc:mysql://localhost:3306/specific_database" ( if your database is on a different server than localhost, make the necessary change.  As well, replace "specific_database" with whatever database name you want to connect to ), our MySQL User, in this case "root", and our MySQL User Password, in this case no password.  The return type of getConnection() is a Connection type.

So, at this point, we've successfully set up our driver, and our connection.  What we need next is to set up our SQL Statement that we want to send to our database.  This is taken care of via the java.sql Statement:
Statement stmt = con.createStatement();
The java.sql package's Connection interface offers a createStatement() method:
Statement createStatement() throws SQLException
that create's a Statement object for sending SQL statements to the database.  SQL statements without parameters are normally executed using Statement objects.  If the same statement is to be executed many times, it might be more efficient to instead utilize a PreparedStatement object.  Anyway, by calling this method on the previously created Connection object, we are returned a Statement object.

Now, we can take this statement object, and fill it with an SQL query using the Statement Interface's executeQuery() method:
ResultSet executeQuery( String sql ) throws SQLException
which as you can see returns a ResultSet type, which brings us to our next line of code:
ResultSet rs = stmt.executeQuery(query);
The ResultSet Interface ( of java.sql ) represents a table of data from our databases result set. The ResultSet object maintains a cursor pointing to its current row of data. Initially, this cursor is positioned before the first row. The next() method moves the cursor to the next row, and it returns false when there are no more rows, so it can be used in a while loop to iterate through the result set... though we're not using it for that here. Getting back on point, that last line of code injected our SQL query, that we sent into our method, into the Statement object's executeQuery() method, and the return result from that query being executed was of type ResultSet. The result from the query ( now in our ResultSet object ) is ready to be examined, which brings us to the following line of code in our method:
if ( rs.next() ) result = rs.getString("modelLine");
The above line essentially says, of course, if there is any data in our result set, then ( if ) there is a column labeled, "modelLine" in the returned data row, assign its contents to our 'result' variable. I'll break this down just a bit further.

We sent an SQL query into our method ( at the beginning of this post ).  Let's say that SQL was, "SELECT * FROM products LIMIT 1".  Let's also say that our products table has a column called, "modelLine", that lists the various model's of goods we sell.  Imagine that under the column "modelLine" we have the model "gizmo" listed, and the row with our "gizmo" model was returned by our SQL query.  So what we have is, within our ResultSet variable, rs, a row of data from our database with the various columns and their associated data, one of which is the column "modelLine", and its associated field, "gizmo".  In the line of code above, our if statement checks rs.next() and it returns true, as we did in fact receive a line of data back.  It then runs the associated line of code that will assign variable 'result' the "modelLine" column's field of data, "gizmo".  So, variable result now holds "gizmo", and it is returned from the method.  The ResultSet Interface actually has a number of methods for retrieving data from a result set.  The method being used here, getString( String columnLabel ) is joined by many others for getting at various types of data, and also for checking rows as well as columns.  Have a look at the API ( linked at the bottom of this post ).

The catch block is Java 7 SE style, which allows all the various kinds of errors that might be thrown to be on a single line, the only thing new there is the Java 7 syntax.

So, this conclude's a walk through the various API calls involved in a basic SQL connection with Java.  Have a look at the API.  There's a whole lot more that can be done.

http://docs.oracle.com/javase/7/docs/api/

Comments

Popular posts from this blog

Install current SBCL on OS X

You must have Command Line Tools installed. If you don't , this tutorial is not for you. Google: installation of XCode and Command Line Tools. Normally, I use brew to install things (when it offers a solution), but in this case the keg version was a couple minor version's off. And, there had been sufficient addition's that motivated me to want the current release. So, building from source was the path of least resistance. First, what not to do : The note's caution against using OS X's Terminal , as their make.sh script pukes a shit-ton of text during the build, and according to them, it can slow the build. I did not experience an issue with this, compared to other builds I've done in the past.   BUT , they also say build can be accomplished with other LISP's installed (you must have a lisp installed prior to building). OMFG , unless you want to wait a month of Sunday's, my experience building with CLISP was slower than the Molasses in January.  D

React Simplicity

This is just a quick intro to React to show how easy it is on a very basic level. React is often compared to Angular, but the two are very different: Angular is more of a framework , whereas React is more of a library . So, with React, we can make Components, and in so doing, we can intersperse plain Javascript to instill behavior. This article is not showing (or using) best practices, or a recommended structure. It's purpose is only to show how easy the basic mechanics of React are. Let's grab the getting started cli from React's page npm install -g create-react-app create-react-app my-app cd my-app npm start After this is done, and you have the project displayed in your browser, let's experiment. A boiler-plate header we can use for each new class can be as simple as: /src/Foo.js import React, { Component } from 'react'; class Foo extends Component { render(){ return(); } } export default Foo; So, all that we need to change to get st

Dead Simple React.js with Meteor

I spent a little time exploring the patterns involved in using React.js with Meteor. It's incredibly easy, it turns out. I'll show some examples here. The setup: meteor add kadira:flow-router npm install react react-dom react-mounter npm install react-addons-pure-render-mixin meteor add react-meteor-data Then of course remove all blaze related meteor packages. Ok, Some basic component patterns: Let's create one that accepts a single argument: Hello.jsx import React from 'react'; export const Hello = ({name}) => ( <div>Hello, {name}</div> ); That's all there is to it. Now, let's see a pattern for a component that takes two arguments. We can see that to add further arguments, we can just tack them on after the first two: TwoArgs.jsx import React from 'react'; export const TwoArgs = ({one, two}) => ( <div> <h2>TwoArgs!</h2> <h3>One is: {one}</h3> <h3>Two is: {two}&