将R连接到postgreSQL数据库

10

我正在尝试将R连接到PostgreSQL数据库。以下是我在R中尝试过的内容:

require("RPostgreSQL")

pw<- {
  "password"
}

# loads the PostgreSQL driver
drv <- dbDriver("PostgreSQL")
# creates a connection to the postgres database
# note that "con" will be used later in each connection to the database
con <- dbConnect(drv, dbname = "DBname",
                 host = "localhost", port = 5432,
                 user = "user", password = pw)
rm(pw) # removes the password

# check for the test_table
dbExistsTable(con, "test_table")
# FALSE >>> Should be true

我无法弄清楚为什么它没有正确连接到我的数据库。我知道数据库在我的电脑上,因为我可以在终端和pgAdmin4中连接它。非常感谢任何帮助。

谢谢


你需要端口5436吗? - vagabond
1
当您执行dbListTables(con)时,会得到什么结果? - vagabond
这样就给了我我的表格。看起来连接是正常的。我不确定为什么它一直给我错误的答案。在提问之前,我应该先尝试查询。感谢您的帮助。 - erik12324
顺便提一下,您可以将您的秘密放在.Renviron文件中,并使用Sys.getenv加载它们。 - Bulat
test_table 是否会在 dbListTables() 中输出,如 @vagabond 所建议的?请注意:Postgres 区分大小写。 - Parfait
离题了,但也可以看看dplyr https://cran.r-project.org/web/packages/dplyr/vignettes/databases.html... 对于复杂的连接和长查询,其语法比SQL更容易。 - David LeBauer
3个回答

11

我在使用DBIRPostgres包的组合时取得了更好的成功,并且我知道RPostgreSQL在一段时间没有进行任何更改后,于五月份发布了一个新版本。RPostgres非常活跃。

## install.packages("devtools")
#devtools::install_github("RcppCore/Rcpp")
#devtools::install_github("rstats-db/DBI")
#devtools::install_github("rstats-db/RPostgres")

library(RPostgres)
library(DBI)

pw<- {
  "password"
}

con <- dbConnect(RPostgres::Postgres()
     , host='localhost'
     , port='5432'
     , dbname='DBname'
     , user='user'
     , password=pw)


rm(pw) # removes the password

dbExistsTable(con, "test_table")

9
install.packages("RPostgreSQL")
require("RPostgreSQL")
# this completes installing packages

# now start creating connection
con <- dbConnect(dbDriver("PostgreSQL"),
                 dbname = "dbname",
                 host = "localhost",
                 port = 5432,
                 user = "db_user",
                 password = "db_password")
# this completes creating connection

# get all the tables from connection
dbListTables(con)

0

一个问题可能是表权限

GRANT ALL PRIVILEGES ON your_table TO user

your_tableuser替换为您自己的凭据

您可以从\dt获取table,从\du获取user


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,