简体   繁体   English

从 R 连接到 Microsoft SQL 服务器

[英]Connecting to Microsoft SQL server from R

The following Python script works.以下 Python 脚本有效。

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.我需要将它移植到 R (从 Rstudio 运行),但无法弄清楚。 I prefer to use native R implementation, rather than reticulate package.我更喜欢使用本机 R 实现,而不是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查看https://db.rstudio.com/databases/microsoft-sql-server/我不确定如何填充他们提供的示例中的字段

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 Trusted_Connection = "True"成功了

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. “驱动程序”是 ODBC 驱动程序的名称,您可能会在 ODBC 数据源应用程序中看到。 For example, on Windows the standard SQL Server driver that comes with the OS is SQL Server .例如,在 Windows 上,操作系统附带的标准 SQL 服务器驱动程序是SQL Server You can also install one from here which will be Microsoft ODBC Driver 17 for SQL Server .您也可以从这里安装一个,它将是Microsoft ODBC Driver 17 for SQL Server

The other arguments are basically the same as for your Python example.其他 arguments 与您的 Python 示例基本相同。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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