Search code examples
rpostgresqlodbc

R ODBC DBI error: database does not exist


I'm working on a Mac and trying to connect to my remote Postgres database in R Studio.

Error

First, the error: Error: nanodbc/nanodbc.cpp:1021: 00000: FATAL: database "db_name" does not exist

Steps taken

I first installed the necessary dependencies using homebrew:

brew install unixodbc

brew install psqlodbc

Then set up my .ini files to contain the following:

odbcinst.ini:

[PostgreSQL Driver]
Driver          = /usr/local/lib/psqlodbcw.so

odbc.ini:

[PostgreSQL]
Driver              = PostgreSQL Driver
Database            = test_db
Servername          = localhost
UserName            = postgres
Password            = password
Port                = 5432

In R, running the following line, to check if my driver is installed correctly, produces the expected result:

> odbc::odbcListDrivers()
               name attribute                       value
1 PostgreSQL Driver    Driver /usr/local/lib/psqlodbcw.so

I then try to connect to the database (actual names/host/pw changed), which then produces an error that the database "does not exist". All the parameters are correct, so I'm not sure what's going on. Could it be some kind of firewall/ssh protection I've set on the server side? Any help would be appreciated, I am but a humble biologist who is a bit out of my depth here.

> con <- dbConnect(odbc::odbc(),
+                  driver = "PostgreSQL Driver",
+                  database = "db_name",
+                  uid = "db_user",
+                  pwd = "db_pass",
+                  host = "123.456.78.910",
+                  port = 5432)
Error: nanodbc/nanodbc.cpp:1021: 00000: FATAL:  database "db_name" does not exist

Solution

  • A much later answer to my own question: after shelving this project for a few months, I came back to it and tried a different driver approach using the RPostgres package. Specifically, rather than messing around with the odbc driver and .ini file, I instead tried RPostgres::Postgres().

    drv <- RPostgres::Postgres()
    db <- DBI::dbConnect(drv = drv, 
                   user = "user",
                   password = "pwd",
                   dbname = "dbname",
                   host = "123.456.78.910")
    DBI::dbGetQuery(db, "select * from my_table")