JRuby Connection to AS400 DB

JRuby Connection to AS400 DB

Hello friend, I suspect that by you visiting you are running in to the same issues I was having trying to get a database connection working using JDBC in JRuby. After that you may also be interested in the connecting to AS400 part. Please note that with a few tweaks of this example you can also connect to some other types of databases. I will note where as we go along.

When coding the first thing we need to do is get our environment set up properly. At the time of this writing I am using JRuby-1.7.4. If you have JRuby ready to go the next thing that we will need is the JDBC Driver that does the leg work of connecting to the AS400 DB. I like to use the JTOpen JDBC driver to connect. You can get that at http://jt400.sourceforge.net/. Once you download the driver unzip it and look through the files for a jtopen.jar and copy it to a lib folder within your project directory. If you are wanting a different type of db you can search for a JDBC driver that would be appropriate.

Lets make this thing work. We will start off by requiring java and our jar file that we just got.

require 'java'
require 'lib/jt400.jar'

Now that we have our list of requirements for the ruby file we can begin defining our class. In this section if you are using a different type of db your class definition will be different. For example MySql would be com.mysql.jdbc.Driver. From what I have read java_import is a relative new function to create instances of classes. If you have issues with the code saying ClassNotFoundException try the java.lang version commented out in the code example.

java_import 'com.ibm.as400.access.AS400JDBCDriver'

# To use on older versions of JRuby
# driverclass="com.ibm.as400.access.AS400JDBCDriver"
# java.lang::Class.forName(driverclass).newInstance

Once we have defined out class then we can build the connection to the db.

  user = "someuser"
  pass = "somepass"
  conn = java.sql.DriverManager.getConnection(
      "jdbc:as400://server;naming=sql;errors=full", 
      user, 
      pass)

Lets have some fun and pull some data.

stmt = conn.createStatement
  rs = stmt.executeQuery("select name from table")
  while (rs.next) do
   puts rs.getString("name")
  end

Hey don’t leave yet you need to clean up your house a little bit.

rs.close
stmt.close
conn.close()

Want to see it all put together? Take a look on GitHub