R基础学习(一)-- 连接mysql数据库

时间:2021-02-16 13:16:17

测试环境:win10+RStudio

(1)在Console加载两个插件

>install.packages('DBI')

Installing package into ‘C:/Users/lmei/Documents/R/win-library/3.5’
(as ‘lib’ is unspecified)
trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.5/DBI_1.0.0.zip'
Content type 'application/zip' length 884354 bytes (863 KB)
downloaded 863 KB

package ‘DBI’ successfully unpacked and MD5 sums checked

The downloaded binary packages are in
C:\Users\lmei\AppData\Local\Temp\Rtmp6Fwdfk\downloaded_packages

>install.packages('RMySQL')
Installing package into ‘C:/Users/lmei/Documents/R/win-library/3.5’
(as ‘lib’ is unspecified)trying URL 'https://cran.rstudio.com/bin/windows/contrib/3.5/RMySQL_0.10.15.zip'Content type 'application/zip' length 2371644 bytes (2.3 MB)downloaded 2.3 MB package ‘RMySQL’ successfully unpacked and MD5 sums checked The downloaded binary packages are in C:\Users\lmei\AppData\Local\Temp\Rtmp6Fwdfk\downloaded_packages

(2)编写R测试脚本ConnectMySQL.R,然后点击RUN

library(RMySQL)
conn <- dbConnect(MySQL(), dbname = "test", username="root", password="123456",client.flag=CLIENT_MULTI_STATEMENTS)
users = dbGetQuery(conn, "SELECT * FROM tb_user")
dbDisconnect(conn)
print(users)

Console输出

> library(RMySQL)
> conn <- dbConnect(MySQL(), dbname = "test", username="root", password="123456",client.flag=CLIENT_MULTI_STATEMENTS)
> users = dbGetQuery(conn, "SELECT * FROM tb_user")
> dbDisconnect(conn)
[1] TRUE
> print(users)
  id name
1  1  Tom

mysql连接读取成功!