2016-11-16 108 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)