Use R to access a mysql db

It’s fairly simple to connect to a MySQL database using R.

You may need to install the RMySQL library. Use the Package Manager to do so.

# require the mysql interface
m <- dbDriver("MySQL")

#what database do you want to connect to
#this is just like Python and Perl connections
con <- dbConnect(m, password="your-passwd", db="your-db")

# prepare and send a query
rs <- dbSendQuery( con, statement = "select x from y where x > 10")

# get all the data. n = -1 means return all data
data <- fetch( rs, n = -1)

# now do something with the data ...

It’s that simple. However, like many things, the more you look at it the more you realise you don’t know. To explore further open R and type ??rmysql or ??mysql.


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s