`
wuhuizhong
  • 浏览: 684565 次
  • 性别: Icon_minigender_1
  • 来自: 中山
社区版块
存档分类
最新评论

Using JRuby with Oracle Database

 
阅读更多

 

This article explains how to use the JRuby programming language with Oracle Database 11g Release 2 . JRuby allows the Java platform and extensive libraries to be augmented with an easy to use and powerful scripting language.

Software Requirements

The following software can be used:

Oracle Database 11g Release 2 Oracle Database Software Downloads
JDK 1.6 or later Java SE Downloads
JRuby 1.5.6 jruby.org
Oracle Database 11g Release 2 JDBC Driver Download ojdbc6.jar from Oracle Database 11g Release 2 JDBC Drivers . Drivers for other versions of Oracle or the JDK can be downloaded from the JDBC Driver Downloads page.
Sample Code The example code can be downloaded here .


The examples will also work with some other versions.

Install each component using its recommended install instructions.

Demonstration Setup

In a terminal window set the Oracle environment and verify Oracle's standard demonstration Human Resources (HR) schema is installed:

$ sqlplus hr/welcome


[. . .]
SQL> select table_name from user_tables;



TABLE_NAME
------------------------------
COUNTRIES
JOBS
EMPLOYEES
LOCATIONS
DEPARTMENTS
JOB_HISTORY
REGIONS


If the schema is not available, see Installing the HR Schema in the Oracle Database Sample Schemas 11g Release 2 (11.2) guide.

Verify JDK 1.6 is installed:

$ java -version


java version "1.6.0_23"
Java(TM) SE Runtime Environment (build 1.6.0_23-b05)
Java HotSpot(TM) 64-Bit Server VM (build 19.0-b09, mixed mode)


Set JRUBY_HOME to the directory where JRuby is installed and verify JRuby runs:

$ export JRUBY_HOME=$HOME/jruby-1.5.6


$ export PATH=$PATH:$JRUBY_HOME/bin


$ jruby -v



jruby 1.5.6 (ruby 1.8.7 patchlevel 249) (2010-12-03 9cf97c3) (Java HotSpot(TM) 64-Bit Server VM 1.6.0_23) [amd64-java]


Copy the Oracle JDBC driver ojdbc6.jar into the $JRUBY_HOME/lib directory:

$ ls -l $JRUBY_HOME/lib


total 20084
-rw-r--r--   1 pas     usergrp  8102598 Dec  3 08:58 jruby.jar
drwxr-xr-x  13 pas     usergrp     4096 Dec  3 08:57 native
-rw-r--r--   1 pas     usergrp  2152051 Feb  7 17:34 ojdbc6.jar


drwxr-xr-x   6 pas     usergrp     4096 Dec  3 08:58 ruby


If JDK 1.5 is installed then copy ojdbc5.jar instead.

Running the Demonstration

The sample code shows several different data operations using JRuby and Oracle Database.

The jruby_plsql.sql file creates a PL/SQL package for showing how to call PL/SQL from JRuby:

-- jruby_plsql.sql

create or replace package emp_pack as
  function get_employee_name (p_employee_id in number) return varchar2;
  procedure delete_department (p_department_id in number);
end emp_pack;
/
show errors;

create or replace package body emp_pack as

  function get_employee_name (p_employee_id in number) return varchar2 is
    l_name varchar2(46) := null;
  begin
      select first_name || ' ' || last_name
        into (l_name)
        from employees
        where employee_id = p_employee_id;
      return l_name;
  end get_employee_name;

  procedure delete_department (p_department_id in number) is
  begin
    delete from departments where department_id = p_department_id;
    commit;
  end delete_department;

end emp_pack;
/
show errors;


The package can be installed using SQL*Plus:

$ sqlplus hr/welcome


SQL> @jruby_plsql.sql



Package created.

No errors.

Package body created.

No errors.


Verify installation by explicitly calling the package:

SQL> select emp_pack.get_employee_name(199) from dual;



EMP_PACK.GET_EMPLOYEE_NAME(199)
-----------------------------------
Douglas Grant


The file jdbc_connection.rb contains code for connecting to the database using the Oracle JDBC driver.

It creates a new JRuby class OracleConnection that exposes attributes of DriverManager which is responsible for connecting to Oracle via the registered subprotocol OracleDriver.

# jdbc_connection.rb

require 'java'

java_import 'oracle.jdbc.OracleDriver'
java_import 'java.sql.DriverManager'

class OracleConnection

  @conn = nil

  def initialize (user, passwd, url)
    @user = user
    @passwd = passwd
    @url = url

    # Load driver class
    oradriver = OracleDriver.new

    DriverManager.registerDriver oradriver
    @conn = DriverManager.get_connection url, user, passwd
    @conn.auto_commit = false

  end

  # Add getters and setters for all attrributes we wish to expose
  attr_reader :user, :passwd, :url, :connection

  def close_connection()
    @conn.close() unless @conn
  end

  def prepare_call(call)
    @conn.prepare_call call
  end

  def create_statement()
    @conn.create_statement
  end

  def prepare_statement(sql)
    @conn.prepare_statement sql
  end

  def commit()
    @conn.commit
  end

  def self.create(user, passwd, url)
    conn = new(user, passwd, url)
  end

  def to_s
    "OracleConnection [user=#{@user}, url=#{@url}]"
  end
  alias_method :to_string, :to_s

end


Edit test_oracle.rb to define the HR schema username, password and connection string. This example shows the database is running on the local machine with the service name of orcl.

The file shows four common uses of SQL and PL/SQL.

# test_oracle.rb

require 'jdbc_connection'

# Edit these for your database schema
user   = "hr

"
passwd = "welcome

"
url    = "jdbc:oracle:thin:@localhost/orcl

"

# Helpers to call our PL/SQL package
PLSQL_BLOCK_FUNCTION_CALL = <<EOF
begin
  :1 := emp_pack.get_employee_name(:2);
end;
EOF

PLSQL_BLOCK_PROCEDURE_CALL = <<EOF
begin
  emp_pack.delete_department(:1);
end;
EOF

print "Run at #{Time.now} using JRuby #{RUBY_VERSION}\n\n"

insert_stmt, select_stmt, rest, delete_stmt, function_stmt = nil

begin
  conn = OracleConnection.create(user, passwd, url)
  # Display connection using the to_s method of OracleConnection
  puts conn, "\n"

  # Insert a new Department
  puts "1. Inserting department 281 into the DEPARTMENTS table"
  insert_sql = "insert into departments values (:1, :2, NULL, NULL)"
  insert_stmt = conn.prepare_statement(insert_sql)
  insert_stmt.set_int    1, 281
  insert_stmt.set_string 2, "JRuby Department"
  insert_stmt.execute
  conn.commit

  # Select all departments
  puts "2. Showing all DEPARTMENTS rows"
  select_sql = "select department_id, department_name from departments order by 1"
  select_stmt = conn.create_statement
  rset = select_stmt.execute_query select_sql
  while (rset.next)
    puts "    Department [#{rset.getInt(1)}, #{rset.getString(2)}]"
  end

  # Call a PL/SQL package function to display an employee name
  puts "3. Finding name of employee 200"
  function_stmt = conn.prepare_call PLSQL_BLOCK_FUNCTION_CALL
  function_stmt.set_int 2, 200
  function_stmt.register_out_parameter 1, 12
  function_stmt.execute_update
  puts "    Employee 200 is #{function_stmt.get_string 1}\n"

  # Call a PL/SQL package procedure to delete a department record
  puts "4. Deleting department 281 from the DEPARTMENTS table"
  delete_stmt = conn.prepare_call PLSQL_BLOCK_PROCEDURE_CALL
  delete_stmt.set_int 1, 281
  delete_stmt.execute_update

rescue
    puts "\n** Error occured **\n"
    puts "Failed executing Oracle demo from JRuby ", $!, "\n"

ensure
   # We have to ensure everything is closed here.
   if (!insert_stmt.nil?)
    insert_stmt.close
   end
   if (!select_stmt.nil?)
    select_stmt.close
   end
   if (!rset.nil?)
    rset.close
   end
   if (!delete_stmt.nil?)
    delete_stmt.close
   end
   if (!function_stmt.nil?)
    function_stmt.close
   end

   conn.close_connection
end

print "\nEnded at #{Time.now}\n"


After connecting, the file uses the exposed OracleConnection attributes to show these database operations: 

  • Inserting a new department 281. The department identifier and name are bound, allowing efficient use of database resources.
  • Querying all department records.
  • Calling a PL/SQL function to find an employee name. The name is returned as an "OUT" parameter of the anonymous PL/SQL block in PLSQL_BLOCK_FUNCTION_CALL.
  • Deletion of the newly created department 281 by calling a PL/SQL procedure.


Run the test program with JRuby:

$ jruby test_oracle.rb


Run at Fri Feb 11 14:54:25 -0800 2011 using JRuby 1.8.7

OracleConnection [user=hr, url=jdbc:oracle:thin:@localhost/orcl]

1. Inserting department 281 into the DEPARTMENTS table
2. Showing all DEPARTMENTS rows
    Department [10, Administration]
    Department [20, Marketing]
    Department [30, Purchasing]
    Department [40, Human Resources]
    Department [50, Shipping]
    Department [60, IT]
    Department [70, Public Relations]
    Department [80, Sales]
    Department [90, Executive]
    Department [100, Finance]
    Department [110, Accounting]
    Department [120, Treasury]
    Department [130, Corporate Tax]
    Department [140, Control And Credit]
    Department [150, Shareholder Services]
    Department [160, Benefits]
    Department [170, Manufacturing]
    Department [180, Construction]
    Department [190, Contracting]
    Department [200, Operations]
    Department [210, IT Support]
    Department [220, NOC]
    Department [230, IT Helpdesk]
    Department [240, Government Sales]
    Department [250, Retail Sales]
    Department [260, Recruiting]
    Department [270, Payroll]
    Department [281, JRuby Department]
3. Finding name of employee 200
    Employee 200 is Jennifer Whalen
4. Deleting department 281 from the DEPARTMENTS table

Ended at Fri Feb 11 14:54:32 -0800 2011


If the test is changed to insert department 100 instead of 281, an error stack will be displayed:

** Error occurred **
Failed executing Oracle demo from JRuby
java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint (HR.DEPT_ID_PK) violated

 

Congratulations, you have just learned how to access an Oracle 11g Release 2 database using JRuby!

分享到:
评论

相关推荐

    ruby连接oracle驱动

    ruby连接oracle驱动包,支持32位与64位操作系统 Developing applications ...Build Ruby and Ruby on Rails applications using the ruby-oci8 driver or JRuby with the Oracle Enhanced Adapter for ActiveRecord.

    Deploying with JRuby: Deliver Scalable Web Apps using the JVM

    Deploying with JRuby: Deliver Scalable Web Apps using the JVM

    jruby1.7.8版本呢

    **JRuby 1.7.8 版本详解** JRuby 是一个开源的、高性能的 Ruby 解释器,它能够将 Ruby 代码编译成 Java 字节码,从而在 Java 虚拟机(JVM)上运行。JRuby 的出现使得 Ruby 开发者能够利用 JVM 的强大功能和丰富的库...

    jruby-src-1.0

    标题“jruby-src-1.0”指的是JRuby的一个特定版本——1.0的源代码。JRuby是一种实现Ruby编程语言的Java版本,它允许在Java平台上运行Ruby代码,同时也支持与Java应用程序进行无缝集成。这个压缩包“jruby-src-1.0....

    org.jruby.rar

    标题 "org.jruby.rar" 暗示我们正在讨论一个与 JRuby 相关的压缩文件,其中可能包含了 JRuby 的源代码、库文件或者其他相关资源。JRuby 是一种 Java 实现的 Ruby 解释器,它允许 Ruby 代码在 JVM(Java 虚拟机)上...

    如何安装与配置JRuby

    **JRuby 安装与配置指南** JRuby 是一个基于 Java 平台的 Ruby 实现,它允许开发者利用 Ruby 语言的优势同时享受 Java 生态系统的强大功能。在本文中,我们将详细探讨如何安装和配置 JRuby,特别是针对 JRuby 1.1.2...

    jruby-bin-1.3.1.zip

    JRuby是Java平台上的一个实现,它允许开发者在Java虚拟机(JVM)上运行Ruby编程语言。这个“jruby-bin-1.3.1.zip”压缩包是JRuby的一个早期版本,专为Ruby语言的研发提供必要的工具和环境。在这个版本中,重点是兼容...

    jruby_windows1.7and bin1.7

    jruby安装包 和 jruby的lib库 JRuby是面向Ruby、基于Java虚拟机(JVM)的一种解释程序,它结合了Ruby语言的简易性和功能强大的JVM的执行机制,包括与Java库 全面集成。Rails彻底加快及简化了Web应用的开发,不过它让...

    JRuby在Java测试中的应用

    ### JRuby在Java测试中的应用 #### JRuby简介 JRuby是一种使Ruby语言能在Java平台上运行的实现方式。它不仅保留了Ruby语言简洁且强大的特性,还充分利用了Java平台的强大功能,如性能优化、垃圾回收机制等。由于...

    jRuby On Rails WEB2.0

    《jRuby on Rails WEB2.0》:将Ruby on Rails融入Java平台的实践指南 《jRuby on Rails WEB2.0》是一部由Ola Bini撰写的书籍,深入探讨了如何将Ruby on Rails这一敏捷开源框架与Java平台相结合,以构建高效、灵活的...

    jruby_windows_1_6_4安装文件

    **JRuby:Ruby on Windows的完美融合** JRuby是一个开源的、基于Java平台的Ruby语言实现,它允许开发者在Ruby环境中使用Java类库,并且可以让Java应用程序无缝地调用Ruby代码。标题中的“jruby_windows_1_6_4安装...

    jruby-bin-0.9.0.tar.gz

    2. **Java平台**:Java平台由Sun Microsystems(现在归Oracle所有)开发,包括Java虚拟机(JVM)、Java类库和开发工具。JVM允许开发者编写一次代码,到处运行,具有跨平台的特性。 3. **JRUBY**:JRUBY 是 Ruby 的...

    如何监控JRuby脚本的执行

    在IT行业中,尤其是在Java与Ruby混合开发的场景中,JRuby是一个重要的工具,它允许开发者在Java平台上运行Ruby代码。由于JRuby是基于JVM(Java Virtual Machine)的,因此可以利用Java生态中的各种工具来对其进行...

    jruby-dist-9.1.15.0-bin.zip

    It is expected to be compatible with Ruby 2.3.x and stay in sync with C Ruby. JRuby 9.1.15.0 is our latest release… Major features of JRuby 9000: Ruby 2.x compatibility A new optimizing runtime ...

    jruby-1.3.1.jar

    jruby-1.3.1.jar包 解决org.jruby.exceptions.JumpException 等报错

    Ruby-JRuby一个Ruby语言的Java实现

    JRuby的版本"jruby-jruby-7bee00d"可能是一个特定的Git提交版本,这表明它是一个开发版本,可能包含了最新的功能和改进。通常,这样的版本会包含一些实验性的特性,对于开发者来说,他们可以提前试用新功能并提供...

    jruby-complete-1.7.19.jar

    jruby-complete-1.7.19.jar,java版本的ruby解析器

    jruby-1.5.5+OperaWatir+RSpec

    标题 "jruby-1.5.5+OperaWatir+RSpec" 暗示了这是一个关于使用 JRuby 1.5.5 版本、OperaWatir 和 RSpec 进行自动化测试的项目或者资源集合。现在,我们将深入探讨这三个关键组件以及它们在 IT 领域中的应用。 JRuby...

Global site tag (gtag.js) - Google Analytics