You are on page 1of 10

DATABASE CONNECTION

IN
R
By,
Vinoth N
20204012404151
II MCA
PACKAGE

• To make connection with database we need relevant packages.


• Here to work with MySQL, RMySQL package is used.
• To install the package the syntax is
• Install.packages(‘RMySQL’)
• Then run the function
LIBRARY

• To work with the functions in a package we need to load it into R library.


• To load a package library() or require() function is used.
• The syntax is
• library(RMySQL) # To use RMySQL functions
DB CONNECTION

• To made a DB Connection the function called dbConnect is used.


• The syntax for MySQL DB connection is
• mydb=dbConnect(MySQL(),user=‘username',password='Password',dbname=‘dbname',
host=‘host',port=portnumber)
• username= DB user name
• Password= Password used for the DB connection
• dbname= dbname
• host= host name (eg. Localhost - 127.0.0.1)
• portnumber= port number used for the DB (eg.3306)
LIST TABLES

• To list the tables name of a database dbListTables() function is used.


• The syntax is
• dbListTables(dbConnect obj)
• obj eg. Mydb

• This function will list all the tables available in the DB


QUERY
• To run a query in DB via R the function called dbSendquery() is used.
• Syntax is
• runquery dbSendQuery(dbConnect object, Query in string format)
• dbConnect object (eg. mydb)
• Query eg. ‘Select * from employees’

• We could execute all MySQL query using this function


DATASET

• To fetch data from a table fetch() function is used.


• Syntax is
• fetch(dbSendquery obj,n)
• obj eg. runquery
• n denotes number of rows should be fetched from the table
• If n=-1 then all the rows will be fetched
WRITE TABLE

• To write a table inside MySQL DB instead INSERT query we have a function dbwriteTable()
function.
• The syntax is
• dbWriteTable(dbConnect obj, value=dataframe,name=“table name", append=TRUE)
• obj eg. mydb
• dataframe eg. mtcars
• tables name eg. mtcarsTable
• append
• If TRUE, then we could write the dataframe value in an already existing table
• If FALSE, then it will create a new table with the name given. If the table already exists throws an error.
CLOSE CONNECTION

• If the DB connection is created it should be closed to avoid data lose and other issues.
• For that dbDisconnect() function is used.
• The syntax for this function is
• dbDisconnect(dbConnect obj)
• obj eg. mydb
• To close a DB connection we should the dbConnect parameter through the
dbDisconnect function.
THANK YOU

You might also like