一、利用R关联数据库,并进行查询操作,输出到数据表
#Download the package for the database in R
install.packages("RMySQL")
#Load the package
library("RMySQL")
#client.flag设置这样支持批量查询
mysqlconnection = dbConnect(MySQL(), user = '用户名', password = '用户密码', dbname = '数据库名',
host = '服务器地址',client.flag= CLIENT_MULTI_STATEMENTS)
dbSendQuery(mysqlconnection,'SET NAMES utf8')
sql <- "select * from table"
#给查询结果赋值
res1 <- dbSendQuery(mysqlconnection,sql)
#将数据从远程数据库加载到R中data里,n=-1,取所有行,n=2 取前两行
data<-dbFetch(res1,n=-1)
#清除查询结果
dbClearResult(res1)
#断开连接
dbDisconnect(mysqlconnection)
二、利用R将rdata放入数据库中,新加表
##在MySql中使用函数dbWriteTable()创建表。 如果表已经存在,它将覆盖该表,并将数据帧用作输入。
# Create the connection object to the database where we want to create the table.
#Load the package
library("RMySQL")
#client.flag设置这样支持批量查询
mysqlconnection = dbConnect(MySQL(), user = '用户名', password = '用户密码', dbname = '数据库名',
host = '服务器地址',client.flag= CLIENT_MULTI_STATEMENTS)
dbSendQuery(mysqlconnection,'SET NAMES utf8')
# Use the R data frame "mtcars" to create the table in MySql.
# All the rows of mtcars are taken inot MySql.
dbWriteTable(mysqlconnection, "mtcars", mtcars[, ], overwrite = TRUE)
##删除MySql数据库中的表,将drop table语句传递到dbSendQuery()中,就像我们使用它查询表中的数据一样。
dbSendQuery(mysqlconnection, 'drop table if exists mtcars')