【问题标题】:Connecting to MS SQL Server on a remote desktop from Python从 Python 连接到远程桌面上的 MS SQL Server
【发布时间】:2020-09-03 01:43:34
【问题描述】:

我正在使用 Windows 服务器通过 VBA 使用以下代码连接到托管在远程桌面上的 SQL Server:

Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset

'Open Connection
objMyConn.ConnectionString = "Provider=SQLOLEDB.1;User ID=sa;Password=xxxxx;Persist Security Info=True;Initial Catalog=databaseName;Data Source=192.168.1.xxx;"
objMyConn.Open

目前正在尝试使用 python 通过此代码连接到同一个 SQL Server 数据库:

import pyodbc
server_name='192.168.1.xxx'
db_name='databaseName'
username='sa'
password='xxxxx'
conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};'
                      'Server=server_name;'
                      'Database=db_name;' 
                      'UID=username;'
                      'PWD=password;'
                      'Trusted_Connection=yes;')
cursor=conn.cursor()

回溯:

File "x/test.py", line 6, in <module>
    conn = pyodbc.connect('DRIVER={ODBC Driver 11 for SQL Server};'
pyodbc.OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 11 for SQL Server]Named Pipes Provider: Could not open a connection to SQL Server [53].  (53) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 11 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 11 for SQL Server]A network-related or instance-specific error has occurred while establishing a connection to SQL Server. Server is not found or not accessible. Check if instance name is correct and if SQL Server is configured to allow remote connections. For more information see SQL Server Books Online. (53)')

【问题讨论】:

    标签: python sql sql-server database-connection remote-server


    【解决方案1】:

    您应该省略参数trusted_connection,因为您提供的是 UID 和 PWD。 Trusted_connection 用您当前的 windows 用户值填充 UID 和 PWD 值,因此它可能保留用于主机内的本地连接。 我相信连接字符串应该是这样的:

    'DRIVER={ODBC Driver 11 for SQL Server};'
                          'Server=server_name;'
                          'Database=db_name;' 
                          'UID=username;'
                          'PWD=password;'
    

    【讨论】:

    • 谢谢,但它不起作用,我仍然得到和以前一样的错误。
    • 如果您确定要传递的凭据可能确实是连接错误。您是否尝试过以任何其他方式连接到另一台机器?
    • 添加DSN并通过DSN连接后可以连接:pyodbc.connect('DSN=dsnName;UID=sa;PWD=xxxxx')
    • 在文档中指出“DSN(或数据源名称)允许您在一个地方定义 ODBC 驱动程序、服务器、数据库、登录凭据(可能)和其他连接属性,所以你不必在你的连接字符串中提供它们。”。如果您在使用 DSN 时可以连接,则意味着您的原始连接字符串的某些变量输入错误。或者它可能是驱动程序,因为您没有使用可用的最新驱动程序。
    猜你喜欢
    • 1970-01-01
    • 2021-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-07
    • 1970-01-01
    • 1970-01-01
    • 2018-06-18
    相关资源
    最近更新 更多