2016-11-16 107 views
1

我想将R连接到PostgreSQL数据库。他是我一直在尝试在R:将R连接到PostgreSQL数据库

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中连接到它。任何帮助是极大的赞赏。

感谢

+0

你需要的端口5436? – vagabond

+1

当你dbListTables(con)' – vagabond

+0

时,你会得到什么所以,这给我的表。看起来连接正在工作。我不确定它为什么一直给我一个错误的答案。在提出问题之前,我应该先尝试查询。谢谢您的帮助。 – erik12324

回答

3

我曾在组合与RPostgres包更好的成功与DBI我知道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") 
1
>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)