Java and DB2 in 10 minutes!

By: Ram Vennam

Java and DB2 in 10 minutes!

 java web application which inserts some data into a DB2 database service. If you’re familiar with creating a servlet, you can do this with me in less than 10 minutes.

First, lets create a simple servlet. I used the @Resource annotation to declare the reference to a jdbc resource by its jndi name. Note the lookup name “jdbc/mydb”. When we upload our application to BlueMix, we will create a database for it with the name “mydb”. 

@Resource(lookup = "jdbc/<strong>mydb</strong>")<br>
    private DataSource myDataSource;<p></p>
<p>    protected void doGet(HttpServletRequest request,<br>
            HttpServletResponse response) throws ServletException, IOException {<br>
        try {<br>
            Connection c = myDataSource.getConnection();<br>
            Statement s = c.createStatement();<br>
            s.executeUpdate("CREATE TABLE MYLIBRARY.MYTABLE (NAME VARCHAR(20), ID INTEGER)");<br>
            s.executeUpdate("INSERT INTO MYLIBRARY.MYTABLE (NAME, ID) VALUES ('BlueMix', 123)");<br>
            response.getOutputStream().print("Test Data inserted into "+ c.getMetaData());<br>
        } catch (SQLException e) {<br>
            response.getOutputStream().print("Something went wrong! : " + e.getMessage());<br>
            return;<br>
        }<br>
    }<br>
</p>

I packaged up my servlet into dbtest.war.

Next, I’ll use cf v6 client to target BlueMix, login and push my application.

cf login -a http://api.ng.bluemix.net<br>
cf push &lt;name of your app&gt; -p C:/dbtest.war -m 512M

Next, visit ace.ng.bluemix.net, and add a SQLDB service to your application. Be sure to call it “mydb”. This gets used when the platform generates the necessary server.xml stanzas for the Liberty server. The DB2 driver jars are also automatically added to my application when I deploy it. This liberty buildpack feature is called Auto-Configuration. It avoid the need for you to parse the VCAP_SERVICES variable for the database connection information. 

Go back to the command line and issue the push command again. A re-push is required for the auto-configuration for the SQLDB service to take place. A restart with the UI is NOT enough.

Now, just hit the app in your browser, and the table and data gets inserted into your very own DB2 instance on BlueMix. That’s how simple it is! You don’t have to worry setting up or configuring your database server, client or drivers.

Check out this doc for more detail: https://www.ng.bluemix.net/docs/Liberty/Bind_RDB.html Get the source: https://hub.jazz.net/project/rvennam/Java%20SQLDB%20Sample/overview

Be the first to hear about news, product updates, and innovation from IBM Cloud