Querying a database from within R

For a while now I have been contemplating pulling data from our postgreSQL db directly from R, but just never actually pulled the trigger until today.  What I found was that it was a lot easier than I ever could have imagined.  My laptop was already on the VPN, so I decided to try it locally before deploying our R studio server.  After a bit of researching, I decided to use the the RPostgreSQL CRAN package.  It literally only takes two lines of code and you are ready to go.

drv <- dbDriver("PostgreSQL")
con <- dbConnect(drv, dbname="database", host="", port="", user="", password="")

The first line installs the driver, in my case a postgreSQL driver, the second line actually connects you to your database.  All you have to do is input the name of the db, host, port, username, and password.  After that, you ready to query!

ba <- dbGetQuery(con,"select * from badass limit 100")

About these ads

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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