標籤:lan 說明文檔 disco table ack art dha href sql資料庫
簡單說下安裝過程,一般不會有問題,重點是RMySQL的使用方式。
系統內容說明
Redhat系統:Linux 460-42.6.32-431.29.2.el6.x86_64
系統編碼:LANG=zh_CN.UTF-8(中文UTF-8格式)
mysql版本號碼:mysql Ver 14.14 Distrib 5.1.73, forredhat-linux-gnu (x86_64) using readline 5.1
安裝mysql
1. 查看是否安裝
yum list installed mysql*
2. 查看現有安裝包
yumlist mysql*
3. 安裝mysqlserver端
yuminstall mysql-devel
yuminstall mysql-server
4. 設定mysql預設字元和引擎
vim/etc/my.cnf
在[mysqld]下加入
default-character-set=utf8
default-storage-engine=INNODB
5. mysql啟動和關閉
/etc/init.d/mysqld start
/etc/init.d/mysqld stop
6. 設定開機mysql啟動
/sbin/chkconfig - - list
/sbin/chkconfig add mysqld
/sbin/chkconfig mysqld on
參考:redhat下mysql安裝與使用
安裝RMySQL
install.packages(“RMySQL”)
使用RMySQL操作資料庫
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")
#寫資料庫表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)
#讀資料庫dbReadTable(con,"fruits")#中文出現亂碼,這是由於字元編碼格式不統一的問題dbSendQuery(con,‘SET NAMES uftf8‘)dbReadTable(con,"fruits")#沒有亂碼問題了
#寫資料表,覆蓋追加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")
#用SQL語句查詢dbGetQuery()和dbSendQuery()兩種方法dbGetQuery(con, "SELECT * FROM fruits limit 3") res <- dbSendQuery(con, "SELECT *FROM fruits")data <- dbFetch(res, n=2) #取前2條資料。n=-1時是擷取全部資料datadata <- dbFetch(res, n=-1) #取餘下全部資料datadbClearResult(res)dbDisconnect(con) #中斷連線
#用SQL語句批量查詢con <- dbConnect(MySQL(),host="host",dbname="test_dw",user="user",password="password",client.flag= CLIENT_MULTI_STATEMENTS) #client.flag設定這樣支援批量查詢dbSendQuery(con,‘SET NAMES utf8‘)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資料庫