R语言使用RMySQL连接及读写Mysql数据库 测试通过
时间:2021-07-01 10:21:17
帮助过:19人阅读
print?
- library(RMySQL)
- help(package=”RMySQL”) #查看RMySQL的说明文档,里面有RMySQL所有可用的方法
- #创建数据库连接
- con <- dbConnect(MySQL(),host="host",dbname="test_dw",user="user",password="password")
- #获取连接信息,查看database下所有表,以及删除testname表
- summary(con)
- dbGetInfo(con)
- dbListTables(con)
- dbRemoveTable(con,"test")
[plain] view plain
copy
print?
- #写数据库表
- fruits <-data.frame(id=1:5,name=c("苹果","香蕉","梨子","玉米","西瓜"),price=c(8.8,4.98,7.8,6,2.1),status=c("无","打折","无","售罄","批发"))
- dbListTables(con)
- dbWriteTable(con,"fruits",fruits)
- dbListTables(con)
[plain] view plain
copy
print?
- #读数据库
- dbReadTable(con,"fruits")#中文出现乱码,这是因为字符编码格式不统一的问题
- dbSendQuery(con,‘SET NAMES utf8‘) #修正,原为:dbSendQuery(con,‘SET NAMES uft8‘)
dbReadTable(con,"fruits")#没有乱码问题了
dbSendQuery(con,‘SET NAMES uft8‘)这个设置一老会提示错误,可能会需要多试几次才行,不知道为什么。
注意:应为:dbSendQuery(con,‘SET NAMES utf8‘)
[plain] view plain
copy
print?
- #写数据表,覆盖追加
- testA <-data.frame(id=1:6,e=c("a","b","c","d","e","f"),c=c("我","的","世","界","变","得"))
- testB <-data.frame(id=7:13,e=c("g","h","i","j","k","l","m"),c=c("奇","妙","跟","难","以","言","喻"))
- #直接写testA写入test表中
- dbWriteTable(con,"test",testA,row.names=F)
- dbReadTable(con,"test")
- #追加写testB追加在test表后
- dbWriteTable(con,"test",testB,append=T,row.names=F)
- dbReadTable(con,"test")
- #覆盖写testB覆盖test表
- dbWriteTable(con,"test",testB,overwrite=T,row.names=F)
- dbReadTable(con,"test")
[plain] view plain
copy
print?
- #用SQL语句查询dbGetQuery()和dbSendQuery()两种方法
- dbGetQuery(con, "SELECT * FROM fruits limit 3")
-
- res <- dbSendQuery(con, "SELECT *FROM fruits")
- data <- dbFetch(res, n=2) #取前2条数据,n=-1时是获取所有数据
- data
- data <- dbFetch(res, n=-1) #取余下所有数据
- data
- dbClearResult(res)
- dbDisconnect(con) #断开连接
[plain] view plain
copy
print?
- #用SQL语句批量查询
- con <- dbConnect(MySQL(),host="host",dbname="test_dw",user="user",password="password",client.flag= CLIENT_MULTI_STATEMENTS) #client.flag设置这样支持批量查询
- dbSendQuery(con,‘SET NAMES uft-8‘)
- sql <- "SELECT * FROM fruits;SELECT * FROM test"
- res1 <- dbSendQuery(con,sql)
- dbFetch(res1, n = -1)
- if (dbMoreResults(con)) {
- res2 <- dbNextResult(con)
- dbFetch(res2, n = -1)
- }
- dbListResults(con)
- dbClearResult(res1)
- dbClearResult(res2)
-
- dbDisconnect(con)
参考:RMySQL数据库编程指南
R语言使用RMySQL连接及读写Mysql数据库 测试通过
标签:inno tool www strong row _for select app 派生