Importing data from database

2017-08-30  本文已影响0人  腾子_Lony

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 theDBIpackage.

dbConnect() creates a connection between your R session and a SQL database. The first argument has to be aDBIdriverobject, 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.

# Load the DBI package

library(DBI)

# Edit dbConnect() call

con <- dbConnect(RMySQL::MySQL(),

dbname = "tweater",

host = "courses.csrrinzqubik.us-east-1.rds.amazonaws.com",

port = 3306,

user = "student",

password = "datacamp")

# Build a vector of table names: tables

tables<-dbListTables(con)

# Display structure of tables

str(tables)

# Import the users table from tweater: users

users<-dbReadTable(con,"users")

# Print users

users

# Get table names

table_names <- dbListTables(con)

# Import all tables

tables <- lapply(table_names, dbReadTable, conn = con)

# Print out tables

tables

上一篇下一篇

猜你喜欢

热点阅读