DB2 queries with R

In shot:
  • R provides RJDBC package. which is really a wrapper of JDBC.
  • For JDBC, we use IBM provided driver db2jcc4.jar .
  • You may like to followed R - Databases tutorial. Keep in mind the DB2 specific adjustments made in R code below.
  • This R-script was tested on Windows 10. It should work on Linux as well.
Usage:
  • Download db2jcc4.jar. Put this jar-file in any folder and remember the path.
  • Adjust db2.R sample code below for your needs.
  • Have R installed in your computer.
  • On Windows, run command: "Path-to_RScript-folder\Rscript.exe" path-to-your-R-file\db2.R


###   STEP 1 **********************************************************************
###          **********************************************************************

### We use JDBC (java database connectivity to connect to DB2 from Java)
### R provides RJDBC, that is a sort of wrapper on top of JDBC  
### You need install it. Please see below

### URL for RJDBC is https://www.rforge.net/RJDBC/

### Download
### The latest RJDBC release is available from CRAN. 
### Run the follow command to intall
### 	install.packages("RJDBC",dep=TRUE) 




###   STEP 2 *********************************************************************
###          *********************************************************************

### You also need JDBC driver itself, for RJDBC to wrap over
### The JDBC driver is just a jar file = "db2jcc4.jar" file.
### Put db2jcc4.jar file at any place you like and memorize the path.  




###   STEP 3 *********************************************************************
###          *********************************************************************

### Note: You can mainly follow https://www.tutorialspoint.com/r/r_database.htm




### This sample was tested on windows, should work on Linux as well.

library(RJDBC)

drv <- JDBC("com.ibm.db2.jcc.DB2Driver",
           "path-to-this-jar/db2jcc4.jar",	### Update path on where you saved db2jcc4.jar !!!!
           identifier.quote="`")
conn <- dbConnect(drv, "jdbc:db2://128.100.137.138:50005/tt_d", user-id, password) 	

print(conn)  
### output is:
### 




### ////////////////////////////////    list tables
result = dbSendQuery(conn, "select TABNAME from syscat.tables where type = 'T'")

# Store the result in a R data frame object. 
data.frame = fetch(result, n = -1)  ### n = -1 means all available records

print(data.frame)





### ////////////////////////////////     select from table
result = dbSendQuery(conn, "select * from SCHEMA.TABLE_NAME")

# Store the result in a R data frame object 
data.frame = fetch(result, n = 5)  ### n = 5 means first five rows

print(data.frame)





###
dbDisconnect(conn)
###                
                

Last updated April 15, 2026