2

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.

2 Answers 2

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

2 Comments

Do not use this solution if you share or publish your code. You invite unauthorized users to access the database by giving out your password.
I fully agree with @Ian. If you share that information with others it is a security risk

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.