R语言连接数据库

一、利用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')
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值