如何从R连接DB2?

时间:2017-09-13 16:14:37

标签: r db2 connection

我们已安装Data Studio 4.1.0.0 Client以访问存储在DB2中的数据。我们已在装有Windows 7 64位的PC上安装了DB2 11.1 64位。

我需要连接到64位R的DB2数据。

我们尝试了以下

library (RODBC)

driver.name <- "{IBM DB2 ODBC DRIVER}"
db.name <- "SBXSHRD"
host.name <- "XX.XXX.X.XX"
port <- "60012"
user.name <- "X20XX4"
pwd <- "SXXXXX01"

#Connection String
con.text <- paste ("DRIVER =", driver.name,
                   "; Database =", db.name,
                   "; Hostname =", host.name,
                   "; Port =", port,
                   "; PROTOCOL = TCPIP",
                   "; UID =", user.name,
                   "; PWD =", pwd, sep = "")

#Connect to DB2
con1 <- odbcDriverConnect (con.text)

top <- sqlQuery (con1,
               "SELECT *
               FROM ODS_CANALES_LINK.VW_OP_D_TRANSACCIONCANAL
               where CODMES_PROC = 201708
               FETCH FIRST 3 ROW ONLY
               ",
               errors = FALSE)

但我在r

中得到以下结果
> con1 <- odbcDriverConnect(con.text)
Warning messages:
1: In odbcDriverConnect(con.text) :
  [RODBC] ERROR: state IM004, code 0, message [Microsoft][Administrador de controladores ODBC] Error de SQLAllocHandle del controlador en SQL_HANDLE_ENV
2: In odbcDriverConnect(con.text) : ODBC connection failed

这里是我们所拥有的DB​​2的详细信息,以及我们在R

中所做的事情的快照

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

RJDBC运作良好。但是......有一次,在完成了docker镜像的重建之后,我得到了所有带有更改列名的结果集,因为它们将名称从jdbc函数getColumnName更改为getColumnLabel。

https://github.com/s-/RJDBC/commit/7f1c1eec25ed90ec5ed71141189b816e2a3c2657

library(RJDBC)
CONSTR <- "jdbc:db2://hostname:446/database"
jcc = JDBC("com.ibm.db2.jcc.DB2Driver", "db2jcc4.jar")

connect <- function() {
   dbConnect(jcc, CONSTR, user="scott", password="tiger")
}

dept <- function() {
  con <-  connect()
  sql <- "SELECT DEPTNO, DEPTNAME FROM DSN8710.dept"      
  rs <- dbSendQuery(con, sql)
  x <- dbFetch(rs)
  dbClearResult(rs)
  # change column names, because the names are not stable!
  names(x) <- c('DEPTNO', 'DEPTNAME')
  dbDisconnect(con)
  x
}