简体   繁体   中英

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 = "firstname.lastname@company.com",
                      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 = "firstname.lastname@company.com",
                      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 = "firstname.lastname@company.com",
                      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?

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")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM