使用R語言鏈接Oracle-ROracle使用舉例(轉)


dbCommit-methods

說明:在Oracle里事務的提交和回滾

 

使用方法:

dbCommit(conn, ...)

dbRollback(conn, ...)

 

舉例:

drv <-dbDriver("Oracle")

con <- dbConnect(drv,"scott", "tiger")

dbReadTable(con,"EMP")

rs <- dbSendQuery(con,"delete from emp where deptno = 10")

dbReadTable(con,"EMP")

if(dbGetInfo(rs, what ="rowsAffected") > 1)

{

warning("dubious deletion-- rolling back transaction")

dbRollback(con)

}

dbReadTable(con,"EMP")

 

 

dbConnect-methods

說明:創建一個數據庫連接方法

 

使用方法:

## S4 method for signature 'OraDriver'

dbConnect(drv, username = "",password = "", dbname = "", prefetch = FALSE,

bulk_read = 1000L, stmt_cache = 0L,external_credentials = FALSE,sysdba = FALSE, ...)

## S4 method for signature 'ExtDriver'

dbConnect(drv, prefetch = FALSE, bulk_read= 1000L, stmt_cache = 0L,

external_credentials = FALSE, sysdba =FALSE, ...)

## S4 method for signature 'OraConnection')

dbDisconnect(conn, ...

 

參數說明:

drv: OraDriver 或 ExtDriver 驅動

conn: 連接oracle對象

username: 數據庫用戶名

password: 數據庫用戶密碼

dbname: 連接oracle數據庫 tns的別名

prefetch: 一個邏輯值,TRUE或FALSE。當設置為TRUE,ROracle會 使用OCI預取緩沖器,以從服務器中檢索附加數據,從而節省通過從OCI提取數據分配一個行緩沖區獲取的RODBI/ ROOCI所需的內存。在使用預取結果取的每一行。通過默認情況下,預取為FALSE且數組提取用於檢索從所述數據服務器。

bulk_read: 一個整數值,表示每次提取的行數。默認 值1000L。當選擇了預取的選項,內存分配用於 預取緩沖器和每次每次會取的行數。當預取 不使用(默認值),內存是分配在RODBI/ ROOCI定義緩沖區。將其設置為一個較大的值會導致分配更多的內存基礎上,在選擇列表中的列和列類型的數量。對於字符類型的列,定義使用最大寬度乘以緩沖區分配 NLS的最大寬度。應用程序應該調整基礎上,該值查詢結果和更大的值將有利於返回大結果的查詢。一個應用程序可以調整為所需要的值。

stmt_cache: 一個整數值,表示語句高速緩存的個數。這意味着游標不需要再次解析就能准備使。默認值是0L。如果stmt_cache值大於0L,則預取的值必須設置為TRUE。

external_credentials: 一個邏輯值,TRUE或FALSE。當設置為TRUE,ROracle會開始OCI會話連接外部憑證進行身份驗證。 缺省值是FALSE。

sysdba: 一個邏輯值,TRUE或FALSE。當設置為TRUE,ROracle會 首先在連接上SYSDBA權限OCI會話。默認 值為FALSE。

 

舉例:

## 在本機創建一個數據庫實例和連接

drv <-dbDriver("Oracle")

con <- dbConnect(drv,username = "scott", password = "tiger")

 

## 運行一個SQL語句

rs <- dbSendQuery(con,"select * from emp where deptno = 10")

 

## 讀取一個結果集到數據框

data <- fetch(rs) ## extractall rows

dim(data)

 

 

## 在連接遠程數據庫的方法:

## create an Oracle Databaseinstance and create one connection to a

## remote database using theSID in the connect string.

drv <-dbDriver("Oracle")

 

## refer to Oracle Database NetServices Administator's Guide for

## details on connect stringspecification.

host <- "myhost"

port <- 1521

sid <- "mysid"

connect.string <- paste(

"(DESCRIPTION=",

"(ADDRESS=(PROTOCOL=tcp)(HOST=",host, ")(PORT=", port, "))",

"(CONNECT_DATA=(SID=",sid, ")))", sep = "")

 

## use username/passwordauthentication

con <- dbConnect(drv,username = "scott", password = "tiger",

dbname = connect.string)

 

## run a SQL statement bycreating first a resultSet object

rs <- dbSendQuery(con,"select * from emp where deptno = 10")

 

## we now fetch records fromthe resultSet into a data.frame

data <- fetch(rs) ## extractall rows

dim(data)

 

 

dbDriver-methods

說明:Oracle驅動的初始化和關閉

 

使用方法:

## S4 method for signature 'OraDriver'

dbUnloadDriver(drv, ...)

## S4 method for signature 'ExtDriver'

dbUnloadDriver(drv, ...)

 

舉例:

# create an Oracle instance

drv <-dbDriver("Oracle")

con <- dbConnect(drv,"scott", "tiger")

res <- dbSendQuery(con,"select * from emp")

fetch(res, n = 5)

fetch(res)

dbClearResult(res)

dbUnloadDriver(drv)

 

 

dbGetInfo-methods

說明:獲取對象的信息的函數

 

舉例:

drv <-dbDriver("Oracle")

con <- dbConnect(drv,"scott", "tiger")

rs <- dbSendQuery(con,"select * from emp")

dbGetStatement(rs)

dbHasCompleted(rs)

dbGetInfo(rs)

 

# DBIDriver info

names(dbGetInfo(drv))

 

# DBIConnection info

names(dbGetInfo(con))

 

# DBIResult info

names(dbGetInfo(rs))

 

 

dbListConnections-methods

說明:獲取連接對象的信息的函數

 

使用方法:

## S4 method for signature 'OraDriver'

dbListConnections(drv, ...)

## S4 method for signature 'ExtDriver'

dbListConnections(drv, ...)

## S4 method for signature 'OraConnection'

dbListResults(conn, ...)

 

舉例:

drv <-dbDriver("Oracle")

con1 <- dbConnect(drv,"scott", "tiger")

res1 <- dbSendQuery(con1,"select * from emp where deptno = 10")

res2 <- dbSendQuery(con1,"select * from emp where deptno = 20")

con2 <- dbConnect(drv,"scott", "tiger")

res3 <- dbSendQuery(con2,"select * from dept")

 

## get all active statements

for(con indbListConnections(drv))

for (res in dbListResults(con))

print(dbGetStatement(res))

 

dbReadTable-methods

說明:在數據庫中執行get, assign,exists, remove, objects, and names except的操作

 

使用方法:

## S4 method for signature'OraConnection,character'

dbReadTable(conn, name, schema = NULL,row.names = NULL, ...)

## S4 method for signature'OraConnection,character,data.frame'

dbWriteTable(conn, name, value, row.names =FALSE, overwrite = FALSE,

append = FALSE, ora.number = TRUE, schema =NULL, ...)

## S4 method for signature'OraConnection,character'

dbExistsTable(conn, name, schema = NULL,...)

## S4 method for signature 'OraConnection,character'

dbRemoveTable(conn, name, purge = FALSE,schema = NULL, ...)

## S4 method for signature 'OraConnection'

dbListTables(conn, schema = NULL, all =FALSE, full = FALSE, ...)

## S4 method for signature'OraConnection,character'

dbListFields(conn, name, schema = NULL,...)

 

參數說明:

conn: 連接數據庫的對象

name: 數據庫表名(大小寫敏感)

schema: 數據庫用戶(大小寫敏感)

row.names: 在dbReadTable情況下,這個變量可以是字符串,索引或邏輯矢量指定列中的DBMS表被用作在row.names 輸出data.frame(一個NULL指定的列不應該被用來作為row.names 在輸出中)。默認值為NULL。

          在dbWriteTable的情況下,這個參數應該是一個邏輯值,表明是否row.names應該輸出到輸出DBMS表;如果為true,一個名稱是“row.names”額外的列其將被添加到輸出。默認為FALSE。

 

value: 一個包含數據的寫到表里的data.frame

overwrite: 一個邏輯值,是否覆蓋表中的數據,默認為FALSE

append: 一個邏輯值,是否是追加數據到已存在的表,默認為FALSE

ora.number: 一個邏輯值,指明是否要創建一個表與OracleNUMBER或 BINARY_DOUBLE列當在寫數字數據時。默認值為TRUE。

purge: 邏輯值,指明是否將purge:選項添加到SQL DROPTABLE語句中。

all: 邏輯值,是否查看所有schemas

full: 邏輯值,指明是否生成schema名。當參數都是TRUE時,輸出是一個包含模式名向量,其次是表名。在輸出用矩陣(...,NCOL= 2)產生一個矩陣其中每一行對應於一個表中,列表示的模式名和表名

 

 

ROracle methods such asdbReadTable, dbGetQuery, fetch, and dbWriteTable use the following mapping between R andOracle data types:

●  logical and integer map to Oracle INTEGER

●  numeric maps to Oracle NUMBER if argument ora.number is TRUE orOracle BINARY_DOUBLEif FALSE

●  character maps to Oracle VARCHAR2(4000)

●   Date and POSIXct map to Oracle DATE ROracle - the ROracle package R- the R application POSIXct - the POSIXct class TIMESTAMP TIMESTAMP WITH TIMEZONE TIMESTAMP WITH LOCAL TIME ZONE

●  difftime maps to Oracle INTERVAL DAY TO SECOND

●  list of raw vectors map to Oracle RAW(2000)

●   other R types such as factor are converted to character

 

 

舉例:

con <- dbConnect(Oracle(),"scott", "tiger")

if (dbExistsTable(con,"FOO", "SCOTT"))

dbRemoveTable(con,"FOO")

foo <- dbReadTable(con,"EMP")

row.names(foo) <- foo$EMPNO

 

foo <- foo[,-1]

dbWriteTable(con,"FOO", foo, row.names = TRUE)

dbWriteTable(con,"FOO", foo, row.names = TRUE, overwrite = TRUE)

dbReadTable(con,"FOO", row.names = 1)

dbGetQuery(con, "deletefrom foo")

dbWriteTable(con,"FOO", foo, row.names = TRUE, append = TRUE)

dbReadTable(con,"FOO", row.names = 1)

dbRemoveTable(con,"FOO")

dbListTables(con)

dbListFields(con,"EMP")

if (dbExistsTable(con,"RORACLE_TEST", "SCOTT"))

dbRemoveTable(con,"RORACLE_TEST")

 

# example of POSIXct usage

# A table is created using:

createTab <- "createtable RORACLE_TEST(row_num number, id1 date,

id2 timestamp, id3 timestampwith time zone,

id4 timestamp with local timezone )"

dbGetQuery(con, createTab)

 

# Insert statement

insStr <- "insert intoRORACLE_TEST values(:1, :2, :3, :4, :5)";

 

# Select statement

selStr <- "select *from RORACLE_TEST";

 

# Insert time stamp withouttime values in POSIXct form

x <- 1;

y <- "2012-06-05";

y <- as.POSIXct(y);

dbGetQuery(con, insStr,data.frame(x, y, y, y, y));

 

# Insert date & times stampwith time values in POSIXct form

x <- 2;

y <- "2012-01-0507:15:02";

y <- as.POSIXct(y);

z <- "2012-01-0507:15:03.123";

z <- as.POSIXct(z);

dbGetQuery(con, insStr,data.frame(x, y, z, z, z));

 

 

# Insert list of date objectsin POSIXct form

x <- c(3, 4, 5, 6);

y <- c('2012-01-05','2011-01-05', '2013-01-05', '2020-01-05');

y <- as.POSIXct(y);

dbGetQuery(con, insStr,data.frame(x, y, y, y, y));

dbCommit (con)

 

 

# Selecting data and displayingit

res <- dbGetQuery(con,selStr)

res[,1]

res[,2]

res[,3]

res[,4]

res[,5]

 

dbSendQuery-methods

說明:查詢返回數據庫的結果集

 

舉例:

drv <-dbDriver("Oracle")

con <- dbConnect(drv,"scott", "tiger")

res <- dbSendQuery(con,"select * from emp where deptno = :1",

data = data.frame(deptno = 10))

data <- fetch(res, n = -1)

res2 <- dbSendQuery(con,"select * from emp where deptno = :1",

data1 = data.frame(deptno =10), prefetch=TRUE,

bulk_read=2L)

data1 <- fetch(res2, n = -1)

res3 <- dbSendQuery(con,"select * from emp where deptno = :1",

data2 = data.frame(deptno =10), bulk_read=10L)

data2 <- fetch(res3, n = -1)

res4 <- dbSendQuery(con,"select * from emp where ename = :1",

data3 = data.frame(ename ='SMITH'))

data3 <- fetch(res4, n = -1)

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM