Establish a connection
The first step to import data from a SQL database is creating a connection to it. As Filip explained, you need different packages depending on the database you want to connect to. All of these packages do this in a uniform way, as specified in the DBI
package.
dbConnect()
creates a connection between your R session and a SQL database. The first argument has to be a DBIdriver
object, that specifies how connections are made and how data is mapped between R and the database. Specifically for MySQL databases, you can build such a driver with RMySQL::MySQL()
.
If the MySQL database is a remote database hosted on a server, you'll also have to specify the following arguments in dbConnect()
: dbname
, host
, port
, user
and password
. Most of these details have already been provided.
This is a part of the course
“Intermediate Importing Data in R”
Exercise instructions
- Load the
DBI
library, which is already installed on DataCamp's servers. - Edit the
dbConnect()
call to connect to the MySQL database. Change theport
argument (3306
) anduser
argument ("student"
).
Hands-on interactive exercise
Have a go at this exercise by completing this sample code.
# Load the DBI package
# Edit dbConnect() call
con <- dbConnect(RMySQL::MySQL(),
dbname = "tweater",
host = "courses.csrrinzqubik.us-east-1.rds.amazonaws.com",
port = 0000,
user = "",
password = "datacamp")
This exercise is part of the course
Intermediate Importing Data in R
Parse data in any format. Whether it's flat files, statistical software, databases, or data right from the web.
Many companies store their information in relational databases. The R community has also developed R packages to get data from these architectures. You'll learn how to connect to a database and how to retrieve data from it.
Exercise 1: Connect to a databaseExercise 2: Establish a connectionExercise 3: Inspect the connectionExercise 4: Import table dataExercise 5: List the database tablesExercise 6: Import usersExercise 7: Import all tablesExercise 8: How do the tables relate?What is DataCamp?
Learn the data skills you need online at your own pace—from non-coding essentials to data science and machine learning.