简体   繁体   中英

Connecting to Microsoft SQL server from R

The following Python script works.

import pandas as pd
from sqlalchemy import create_engine

DOMAIN_NAME = "my_domain"
USER = "my_username"
PASSWORD = "my_password"
SERVER = "server_name"
DB = "database_name"

engine = create_engine(f"mssql+pymssql://{DOMAIN_NAME}\\{USER}:{PASSWORD}@{SERVER}/{DB}")

query =sql("""
SELECT Name
FROM Products
""")
pd.read_sql(query, engine)

I need to port it into R (to run from Rstudio), but cannot figure it out. I prefer to use native R implementation, rather than reticulate package.

Looking at https://db.rstudio.com/databases/microsoft-sql-server/ I am not sure how to populate the fields in the example they provide

con <- DBI::dbConnect(odbc::odbc(),
                      Driver   = "[your driver's name]",
                      Server   = "[your server's path]",
                      Database = "[your database's name]",
                      UID      = rstudioapi::askForPassword("Database user"),
                      PWD      = rstudioapi::askForPassword("Database password"),
                      Port     = 1433)

This eventually worked. Trusted_Connection = "True" made the trick

DBI::dbConnect(odbc::odbc(),
             Driver = "SQL Server",
             Server = SERVER,
             Database = DB,
             UID = glue::glue("\\{DOMAIN_NAME}/{USER}"),
             PWD = PASSWORD,
             Trusted_Connection = "True",
             port=1433

)

"Driver" is the name of your ODBC driver, as you might see in your ODBC data sources app. For example, on Windows the standard SQL Server driver that comes with the OS is SQL Server . You can also install one from here which will be Microsoft ODBC Driver 17 for SQL Server .

The other arguments are basically the same as for your Python example.

DBI::dbConnect(odbc::odbc(),
    Driver="SQL Server",
    Server="domain",
    Uid="your-username",
    Pwd="your-password",
    port=1433
)

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