Janjua
Janjua

Reputation: 237

R connecting Postgres

I'm just trying to connect R to PostgreSQL, but I get an error

library("RPostgreSQL")
m <- dbDriver("PostgreSQL")
con <- dbConnect(m)

the error is

Error in postgresqlNewConnection(drv, ...) : 
  RS-DBI driver: (could not connect user@localhost:5432 on dbname "user": FATAL:  role "user" does not exist
)

It looks like access issue to me, but don't know how to resolve if any one can help.

Upvotes: 2

Views: 1312

Answers (2)

Ian
Ian

Reputation: 1165

The database driver needs more information: the address of the database server, the database name, which "role" (i.e. user) you can connect to the database with, and the associated password. Do you know all those?

A good setup is to collect and store all those parameters in a pg service file, labeled with an easy-to-type "service" name. For example:

[xyz]
host=<hostname or ip>
dbname=<database>
user=<role>
password=<password>

Then you can create a connection in R using the service name alone:

library('RPostgreSQL')
con <- dbConnect(PostgreSQL(), dbname = 'postgres://@/?service=xyz')

Save the pg service file in the correct path (~/.pg_service.conf on linux). You can include separate blocks for each service/database you use, so this file shouldn't live in a particular project's directory.

Upvotes: 3

ekstroem
ekstroem

Reputation: 6191

You need to add your credentials in your call do dbConnect. Here is an example

mydb <- dbConnect(m, user="rprimer", password="PASSword",                   
                  dbname="rprimer", host="192.168.1.151")

Try specifying all the necessary information and see if that helps. You'll need to adapt all the arguments to your setup.

Upvotes: 1

Related Questions