Using RStudio Connection Pane to connect with a Po

2019-04-13 00:55发布

问题:

We have a PostgreSQL database at work. Every time I want to connect to it, I'm manually executing the following code to build my connection and it works just fine.

    library(RPostgreSQL)
    con <- dbConnect(dbDriver("PostgreSQL"),
                     dbname   = "company_xy",
                     host     = "db.company_xy.de",
                     port     = 5432,
                     user     = rstudioapi::askForPassword("User"),
                     password = rstudioapi::askForPassword("Password!"))

I now want to start using the Connections pane but despite trying in multiple ways to set it up, I never got it working. This is the process I followed as described in the RStudio documentation:

1.Click on New Connection
2.Select PostgreSQL Unicode(x64)
3.In the parameters window I paste in the following code:

    Driver = "PostgreSQL",
    Server = "db.company_xy.de",
    Database = "company_xy",
    UID = "my_username",
    PWD = "my_password",
    Port = 5432

I always receive the following error message:

Failure. :2.99: unexpected symbol 1: library(DBI) con <- dbConnect(odbc::odbc(), .connection_string = "Driver={PostgreSQL Unicode(x64)};Driver = "PostgreSQL

I tried removing the parenthesis and using different kind of separators between the parameters ({}, ;) but to no end. The drivers for odbc and DBI are installed.

Can anyone spot a coding mistake or did I do it wrong?

回答1:

It should work provided that you remove the double quotes and spaces, and replace the commas by semicolons.

So your parameters window should look like that:

Server=db.company_xy.de;
Database=company_xy;
UID=my_username;
PWD=my_password;
Port=5432;

Note that you don't need to specify the driver since you already chose it when you selected PostgreSQL Unicode(x64) in the previous window.

Actually it seems that the point of this parameters windows is just to build the connection string that you can see below it. So IMO it's more direct to set the connection from your R script (or console):

library(DBI)
con <- dbConnect(
  odbc::odbc(),
  driver = "PostgreSQL Unicode(x64)",
  Server = "db.company_xy.de",
  Database = "company_xy",
  UID = rstudioapi::askForPassword("User"),
  PWD = rstudioapi::askForPassword("Password!"),
  Port = 5432
)

or, if you like connection strings:

library(DBI)
con <- dbConnect(
  odbc::odbc(), 
  .connection_string = "Driver={PostgreSQL Unicode(x64)};Server=db.company_xy.de;Database=company_xy;UID=my_username;PWD=my_password;Port=5432;"
)

but this latter method does not allow you to use rstudioapi::askForPassword.

In both cases the connection will appear in your Connections pane.

Maybe in the future you won't need to use odbc for that: https://community.rstudio.com/t/postgresql-in-connection-tab/1817/4