zesla
zesla

Reputation: 11793

Issue connecting to SQL Server using DBI:dbConnect in R

The first method I tried works. I first defined an ODBC connection my_connection_name with ODBC data source administrator on my windows. Then I use the following code:

library(DBI)
library(odbc)
con <- DBI::dbConnect(odbc(),
                      dsn='my_connection_name',
                      UID = "[email protected]",
                      PWD = "mypassword")

This works fine!

However, when I tried to define the driver, server and database name within the dbConnect function. It fails!

con <- DBI::dbConnect(odbc(),
                      Driver = "ODBC Driver 13 for SQL Server",
                      Server = 'my_server_name',
                      Database = "my_database_name",
                      UID = "[email protected]",
                      PWD = "mypassword",
                      Trusted_Connection = "yes")

I got error:

Error: nanodbc/nanodbc.cpp:950: 08S01: [Microsoft][ODBC Driver 13 for SQL Server]TCP Provider: An existing connection was forcibly closed by the remote host.

Interestingly, when I remove the Trusted_Connection = "yes".

con <- DBI::dbConnect(odbc(),
                      Driver = "ODBC Driver 13 for SQL Server",
                      Server = 'my_server_name',
                      Database = "my_database_name",
                      UID = "[email protected]",
                      PWD = "mypassword")

I got error message like this:

Error: nanodbc/nanodbc.cpp:950: HY000: [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Cannot open server "company.com" requested by the login. The login failed.

I used the same driver, server and database name when I defined the ODBC connection previously.

My authentication option is ActiveDirectoryPassword.

Does anyone know what is going on?

Upvotes: 3

Views: 5403

Answers (1)

Ed Bangga
Ed Bangga

Reputation: 13006

if using Trusted Connection = Yes, you don't need to supply your username and password. your service account will be used to connect to your sql server.

con <- DBI::dbConnect(odbc(),
                      Driver = "ODBC Driver 13 for SQL Server",
                      Server = 'my_server_name',
                      Database = "my_database_name",                    
                      Trusted_Connection = "yes")

Upvotes: 3

Related Questions