将R连接到postgreSQL数据库

时间:2016-11-16 21:27:31

标签: sql r postgresql

我正在尝试将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连接到它。非常感谢任何帮助。

由于

2 个答案:

答案 0 :(得分:3)

>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)

答案 1 :(得分:0)

一个问题可能是表权限

GRANT ALL PRIVILEGES ON your_table TO user

用您自己的凭据替换 your_tableuser

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