2

Using the RPostgreSQL package, is there a way to connect to a remote PostgreSQL instance other than hardcoding the credentials into the dbConnect method?

As far as I can tell, this is the only way to do it:

dbConnect(drv, host='some.com', port='5432', dbname='some-db', user='usr', password='secrecy')

Certainly there's a way to use a connection string or something?

Edit: I mean referencing some file (separate from the source code) or environment variable that contains the connection string. Sort of like .pgpass in my home directory, or DATABASE_URL on heroku. Just some way to avoid having DB credentials in the source code.

3
  • Have a look at the docs for RPostgres - I think I documented what you need there Commented Apr 3, 2015 at 2:42
  • Thanks @hadley. I've looked through these docs cran.r-project.org/web/packages/RPostgreSQL/RPostgreSQL.pdf, but I didn't see any means of connecting using something that doesn't have the credentials right in the source code. Can you point me to such a thing? Commented Apr 3, 2015 at 16:24
  • RPostgres, not RPostgreSQL: github.com/rstats-db/RPostgres/blob/master/R/… Commented Apr 3, 2015 at 19:26

1 Answer 1

1

On Windows at least, in an interactive session you can prompt the user for a name and password with winDialogString.

user <- winDialogString("Enter your username", "")
pwd <- winDialogString("Enter your password", "")
dbConnect(..., user=user, password=pwd)

But what does a connection string do that a function call doesn't? Either way, you still have to hardcode your credentials somewhere.


You can also store the credentials in a file somewhere, and read them in using the usual methods (readLines, scan, read.table etc).

### assuming dbcreds.txt contains the single line "username    password"
cred <- strsplit(readLines("dbcreds.txt"), "[[:blank:]]+")[[1]]
user <- cred[1]
pwd <- cred[2]
dbConnect(..., user=user, pass=pwd)
Sign up to request clarification or add additional context in comments.

2 Comments

You're right about the hardcoded connection string. I guess I meant referencing some file (separate from the source code) or environment variable that contains the connection string. Sort of like .pgpass in my home directory, or DATABASE_URL on heroku.
I may in fact go with something like your solution: prompt the user for input.

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.