Connecting to Oracle DB using Ruby

2020-05-24 20:08发布

问题:

I am stuck with connecting to Oracle DB, have read lots of stuff but no help on result.
I have remote Oracle DB, I am connecting to it using DBVisualizer setting connection like this:

DB Type : Oracle
Driver (jdbc) : Oracle thin
Database URL: jdbc:oracle:thin:@10.10.100.10:1521/VVV.LOCALDOMAIN
UserIdf: SomeUser
Pass: SomePass

Connection works ok.

What I do in Ruby is :

require 'oci8'
require 'dbi'
...

conn = OCI8.new('SomeUser','SomePass','//10.10.100.10:1521/VVV.LOCALDOMAIN')
...

What I get is:

ORA-12545: Connect failed because target host or object does not exist
oci8.c:360:in oci8lib.so

回答1:

the third parameter needs to be the TNS hostname, if you use SQL plus it is also the third parameter in the connectstring, you can find it also in the tnsnames.ora file in the oracle maps

in SQLPlus : connect user/password@hostname;
in oci8 : conn = OCI8.new('SomeUser','SomePass',hostname)

Here a working sample, obfuscated the parameters of course

require 'oci8'
oci = OCI8.new('****','***','****.***')
oci.exec('select * from table') do |record|
  puts record.join(',')
end


回答2:

require 'oci8'
oci = OCI8.new('system','prasad','127.0.0.1:1521')
oci.exec("CREATE TABLE states1 (
           id CHAR(2) PRIMARY KEY,
           name VARCHAR2(15) NOT NULL,
           capital VARCHAR2(25) NOT NULL)")


回答3:

require 'oci8'
oci = OCI8.new('system','prasad','127.0.0.1:1521')
oci.exec("insert into states1  values(1,'prasad','visakhapatnam')")
oci.exec("commit")
oci.exec('select * from states1') do |record|
    puts record.join(',')
end