Accessing MySQL through R

[This article was first published on Playing with R, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
Connecting to MySQL is made very easy with the RMySQL package. To connect to a MySQL database simply install the package and load the library.
install.packages("RMySQL") library(RMySQL)

Connecting to MySQL:
Once the RMySQL library is installed create a database connection object.
mydb = dbConnect(MySQL(), user='user', password='password', dbname='database_name', host='host')

Listing Tables and Fields:
Now that a connection has been made we list the tables and fields in the database we connected to.
dbListTables(mydb)
This will return a list of the tables in our connection.
dbListFields(mydb, 'some_table')
This will return a list of the fields in some_table.

Running Queries:
Queries can be run using the dbSendQuery function.
dbSendQuery(mydb, 'drop table if exists some_table, some_other_table')
In my experience with this package any SQL query that will run on MySQL will run using this method.

Making tables:
We can create tables in the database using R dataframes.
dbWriteTable(mydb, name='table_name', value=data.frame.name)

Retrieving data from MySQL:
To retrieve data from the database we need to save a results set object.
rs = dbSendQuery(mydb, "select * from some_table")
I believe that the results of this query remain on the MySQL server, to access the results in R we need to use the fetch function.
data = fetch(rs, n=-1)
This saves the results of the query as a data frame object. The n in the function specifies the number of records to retrieve, using n=-1 retrieves all pending records.
To leave a comment for the author, please follow the link and comment on their blog: Playing with R.

R-bloggers.com offers daily e-mail updates about R news and tutorials about learning R and many other topics. Click here if you're looking to post or find an R/data-science job.
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.

Never miss an update!
Subscribe to R-bloggers to receive
e-mails with the latest R posts.
(You will not see this message again.)

Click here to close (This popup will not appear again)