Connecting to MySQL from R

人盡茶涼 提交于 2019-12-04 14:35:04

问题


I am trying to connect to MySQL from R. I have installed "8.0.11 MySQL Community Server - GPL" on my machine. In R studio, I have installed RMySQL Library.

When I give the command:

con = dbConnect(RMySQL::MySQL(),user="root", password = "password", dbname="test")

I keep getting the error:

Error in .local(drv, ...) : Failed to connect to database: Error: Unknown database 'test'

I am not sure why it keep giving this error. Any suggestions?


回答1:


Here is a code I use for access to MySQL from R

# 1. Library
library(RMySQL)

# 2. Settings
db_user <- 'your_name'
db_password <- 'your_password'
db_name <- 'database_name'
db_table <- 'your_data_table'
db_host <- '127.0.0.1' # for local access
db_port <- 3306

# 3. Read data from db
mydb <-  dbConnect(MySQL(), user = db_user, password = db_password,
                 dbname = db_name, host = db_host, port = db_port)
s <- paste0("select * from ", db_table)
rs <- dbSendQuery(mydb, s)
df <-  fetch(rs, n = -1)
on.exit(dbDisconnect(mydb))

Please, check how it works on your side.

PS. Looks like you miss 'db_table' parameter.




回答2:


The obvious reason may be "I hope" beacuse you didn't include the host ip. Also I prefer use pool package. Then your connection call may be

library(DBI)
library(RMySQL)
library(pool)

pool <- dbPool(
                  drv = RMySQL::MySQL(),
                  dbname = "db_name",
                  host = "127.0.0.1",
                  username = 'user_name',
                  password = 'password',
                  port = 3306
             )

 onStop(function() {
           poolClose(pool)
         })

Another thing it's better to define user with appropriate privileges on test DB and use this user in the connection call insteade of root as DB connection security best practice.



来源:https://stackoverflow.com/questions/50544230/connecting-to-mysql-from-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!