如何使用RJDBC将R连接到Oracle DB

时间:2018-12-06 10:16:52

标签: r database oracle rjdbc

我正在尝试将R连接到我的Oracle数据库,但是每当我调用以下函数时,都会出现以下错误:

Error in .jcall(drv@jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1],  : 
  java.sql.SQLException: NL Exception was generated

我有2个文件,一个functions.r文件和我的working.r文件。以下是每个文件中的内容。

functions.r

caesi <- function(DB){
  ## Create an Oracle connection to a
  ## remote database using the SID in the connect string.
  drv <- JDBC(driverClass="oracle.jdbc.OracleDriver", classPath="E:/filelocation/ojdbc6.jar")

  ## user details 
  username = "USERNAME" ## Your user name
  password = "PASSWORD" ## Your password

  ## Refer to Oracle Database Net Services Administator's Guide for
  ## details on connect string specification.

  ## Current connection string this will change when we replatform
  host <- "LOCALHOST"
  port <- 1521
  svc <- "rtreports"
  connect.string <- paste("(DESCRIPTION=", " (ADDRESS= (PROTOCOL=TCP)(HOST= ",host,")(PORT=",port,"))","(CONNECT_DATA= (SERVICE_NAME=",svc,")))",sep = "")

  ## Use username/password authentication.
  ErrReturn <- 0  
  return({

    con <-dbConnect(drv,paste0("jdbc:oracle:thin:@localhost:1521:orcll",connect.string),username, password)

  })

} 

Get_Data = function(){
ch_or <- caesi("DB")

data <- dbGetQuery(ch_or, paste0(("SELECT * FROM MYTABLE")))

dbDisconnect(ch_or) 

outcoords <- data
  return(outcoords)
}

和我的working.r文件

#
library(tidyverse)
library(RJDBC)
library(rJava)
library(ggplot2)
library(dplyr)

source("functions.R")

df <- Get_Data()

每当我运行Get_Data时,我都会收到错误消息。我不确定我要去哪里错了,如果有人可以提出建议(如果我是R的新手)会非常感激,如果有人可以提供帮助,我真的会喜欢它。


Nirmala,在进行了请求的更改后,我在代码中注释了以下部分:

## Current connection string this will change when we replatform
  ##host <- "LOCALHOST"
  ##port <- 1521
  ##svc <- "rtreports"
  ##connect.string <- paste("(DESCRIPTION=", " (ADDRESS= (PROTOCOL=TCP)(HOST= ",host,")(PORT=",port,"))","(CONNECT_DATA= (SERVICE_NAME=",svc,")))",sep = "")

,然后将连接线更改为:

con <-dbConnect(drv,paste0("jdbc:oracle:thin:@localhost:1521:orcll"),username, password)

但这现在给我以下错误:

Error in .jcall(drv@jdrv, "Ljava/sql/Connection;", "connect", as.character(url)[1],  : 
  java.sql.SQLException: ORA-01017: invalid username/password; logon denied

即使用户名/密码正确并且可以在sql developer中连接到数据库也可以正常工作。

1 个答案:

答案 0 :(得分:1)

您传递连接URL的方式可能有问题。您正在混合使用长格式和易于连接的URL。您能使用这里显示的URL并尝试一下吗?

jdbc:oracle:thin:@myhost:1521 / myorcldb服务名