Connect to an oracle database using jdbc on JRuby in a jar file
This is how you can use JRuby to connect to an oracle database without requiring Ruby to be installed on the system, but only Java.
The JRuby interpreter and all necessary libraries will be packed into a single executable jar file. This is done “from scratch”, so if you need something more complex, consider gems like warbler, rawr and/or activerecord-jdbc-adapter.
1) Get the Java libraries
Get ojdbc6.jar
from the oracle homepage (you need to create an oracle account…) and the JRuby interpreter:
wget -O jruby.jar https://jruby.org.s3.amazonaws.com/downloads/1.6.7.2/jruby-complete-1.6.7.2.jar
Store them in the same directory.
2) Prepare the jruby.jar
to include oracle’s Java classes
unzip ojdbc6.jar
jar uf jruby.jar oracle
3) Use the boilerplate jdbc code from oracle (optional)
You can use jdbc_connection.rb (scroll down 2/5) from the oracle documentation to abstract away some low level code.
jar uf jruby.jar jdbc_connection.rb
4) Create a jar-bootstrap.rb
file
This is the file that will be invoked when running the jar file from the command line.
touch jar-bootstrap.rb
5) Write some Ruby code that interacts with the database
Create the db connection with the code at (3) or with something like that:
require 'java'
java_import 'oracle.jdbc.OracleDriver'
java_import 'java.sql.DriverManager'
connection = java.sql.DriverManager.getConnection( # might raise errors
"jdbc:oracle:thin:@host:port:db",
"user",
"password"
)
# use connection...
6) Package it all together
cp jruby.jar your.jar
# jar uf your.jar your.rb
jar ufe your.jar org.jruby.JarBootstrapMain jar-bootstrap.rb
You can add more .rb
files to the jar, which can easily be require
d, because the jar root gets added to Ruby’s load path. However, require_relative
won’t work.
7) Run it! :D
java -jar your.jar