watir学习系列--oracle数据库操作

一、插入数据:

 require 'DBI'
require 'jcode'
$KCODE = 's' #设置汉字代码为EUC,windows环境为"s",linux环境为"e"#数据库变量
db_host = 'DBI:OCI8:TEST'
db_user = 'user
db_psw = 'passwpord

dbh = DBI.connect(db_host, db_user, db_psw) #连接数据库
#插入数据
insert_sql = "insert into table values('1','2')"
begin
rs = dbh.prepare(insert_sql)
rs.execute #执行SQL
dbh.commit #提交数据
rs.finish
rescue DBI::DatabaseError => e
puts "Error code : #{e.err}"
puts "Error message: #{e.errstr}"
ensure
dbh.disconnect if dbh
end

 

二、查询数据:

 

require  'DBI'     #加载DBI文件
require  'jcode'
$KCODE = 's'    #设置汉字代码为EUC,windows环境为"s",linux环境为"e"

#数据库变量
db_host      = 'DBI:OCI8:TEST'
db_user      = 'user'
db_psw       = 'password'
select_sql  = "select value1,value2 from table"
begin
   rs = dbh.prepare(select_sql)
    rs.execute                                                               #执行查询
    value_rows                   = rs.fetch_all                      #获取表数据
    column_names_rows  = rs.column_names            #获取表列名
    DBI::Utils::TableFormatter.ascii(column_names_rows,value_rows)  #以表格的格式输出
    DBI::Utils::XMLFormatter.table(value_rows)     #以XML的格式输出
    rs.finish
rescue DBI::DatabaseError => e
    puts "Error code : #{e.err}"
    puts "Error message: #{e.errstr}"
ensure
    dbh.disconnect if dbh
end

 

 

三、删除数据:

 

require 'DBI'
require 'jcode'
$KCODE = 'e'     #设置汉字代码为EUC,windows环境为"s",linux环境为"e"

#数据库变量
db_host      = 'DBI:OCI8:TEST'
db_user      = 'user'
db_psw       = 'password'

dbh = DBI.connect(db_host, db_user, db_psw)  #连接数据库
#删除数据
delete_sql = "delete from table where value1 =? and value2=?"
begin
   rs = dbh.prepare(delete_sql)
   rs.execute('1','2')
   dbh.commit
    rs.finish
rescue DBI::DatabaseError => e
    puts "Error code : #{e.err}"
    puts "Error message: #{e.errstr}"
ensure
    dbh.disconnect if dbh
end

 

 

你可能感兴趣的:(oracle数据库)