T4 L9 Host Program R-1
T4 L9 Host Program R-1
Topic 4 Lesson 9
R connection to the client server model
As of today, there is no standard driver to connect an R
program to a MySQL database
The DBI package separates the connectivity to the DBMS into
a “front-end” and a “back-end”. Applications use only the
exposed front-end API. The back-end facilities that
communicate with specific DBMSs (SQLite, MySQL,
PostgreSQL, MonetDB, etc.) are provided by drivers (other
packages) that get invoked automatically through R’s S4
methods.
R to MySQL
There are a few packages that do connect a R script to a
MySQL database, RMySQL, RODBC, RMariaDB and
RJDBC. ( RMariaDB and RMySQL are supported ) – both
provide the same interface. All such libraries automatically
include the DBI package.
Just like any other R package you must install the package
locally so we can access its methods from our R script
Installing RMySQL
Issue the
command:
install.packages
("RMySQL") to
install
Parameters:
con is the value returned from DbConnect
sql is the query you wish to run on the database
Output: returns a MySQLConnection class
Accessing the requested data
ACCESS data: dbFetch(MySQLResult, n)
Parameters:
MySQLResult is the return variable from dbSendQuery
n maximum number of records to retrieve
Clean up: when done with the results free the allocated space
with dbClearResult(res)
Requesting and Accessing data
REQUEST:dbGetQuery(con, sql) will retrieve data from the
database
con parameter is the value returned from DbConnect
sql parameter is the query you wish to run on the database
It will automatically fetch all data locally and clear the space
for the data. This should be used when the size of the
returning data is small (will not exceed virtual memory of R
program).
Example code (1)
library(RMySQL)
library(tidyverse)
globalUsername <- "root"
globalPass <- ”password"
# 1Settings
db_user <- 'root'
db_password <- ‘password'
db_name <- 'lotrfinal_1'
# 2. Connect to the db
mydb <- dbConnect(MySQL(), user = db_user, password = db_password,
dbname = db_name, host = db_host, port = db_port)
Example code (2)
db_table <- 'lotr_character'
rs <- dbSendQuery(mydb, s)
df <- fetch(rs, n = -1) #-1 represents to read all data
df
dbClearResult(rs)
dbDisconnect(mydb)
Example code (3)
# fetch chunks of data when dealing with large results