gpt4 book ai didi

python - 将 Python 连接到远程 SQL Server

转载 作者:行者123 更新时间:2023-12-02 18:51:15 25 4
gpt4 key购买 nike

我正在尝试将 Python 连接到我们的远程 SQL Server,但没有成功。以下是我使用的代码。

 server = 'server,1433' 
database = 'db'
username = 'username'
password = 'pw'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 17 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute('SELECT top 1 * FROM db.dbo.t_location')
for row in cursor:
print(row)

我们有 2 个服务器。一个是数据库服务器,但我使用连接到数据库服务器的 SQL 应用程序服务器。这是我得到的错误。我正在尝试一个星期,但我不确定我在这里错过了什么。任何帮助将不胜感激

OperationalError: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]TCP Provider: No such host is known.\r\n (11001) (SQLDriverConnect); [08001] [Microsoft][ODBC Driver 17 for SQL Server]Login timeout expired (0); [08001] [Microsoft][ODBC Driver 17 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. (11001)')

添加:

connection_str = ("Driver={SQL Server Native Client 11.0};"
"Server= 10.174.124.12,1433;"
#"Port= 1433;"
"Database=AAD;"
"UID=dom\user;"
"PWD=password;"
)

连接 = pyodbc.connect(connection_str)data = pd.read_sql("select top 1 * from dbo.t_location with (nolock);",connection)

我使用了上面的代码,现在我看到了这个错误。好像可以用,但是登录失败。通常我必须在 SSMS 中使用 Windows 身份验证,一旦我输入我的凭据以登录远程桌面。

('28000', "[28000] [Microsoft][SQL Server Native Client 11.0][SQL Server]用户 'dom\user' 登录失败。(18456) (SQLDriverConnect); [28000] [Microsoft][ SQL Server Native Client 11.0][SQL Server]用户 'dom\user' 登录失败。(18456)")

回答:

我很兴奋终于找到了使用 pymssql 的解决方案。我不知道 pyodbc 没有工作,但我确定我一定是做错了什么。我使用以下代码使用 Python 从远程 SQL 服务器获取数据。

import pymssql

conn = pymssql.connect(
host=r'10.174.124.12',
user=r'dom\user',
password=r'password',
database='db'
)
cursor = conn.cursor(as_dict=True)
cursor.execute('Select top 4 location_id, description from t_location with (nolock)')
data = cursor.fetchall()
data_df = pd.DataFrame(data)

cursor.close()

此时忽略我的代码。我仍然需要做一些清理工作,但这段代码可以工作。

最佳答案

最后,为了回答我的问题,我不得不使用 pymssql,它起作用了。我不必输入让我感到困惑的端口号。感谢大家抽出时间来回答。

import pymssql

conn = pymssql.connect(
host=r'10.174.124.12',
user=r'dom\user',
password=r'password',
database='db'
)
cursor = conn.cursor(as_dict=True)
cursor.execute('Select top 4 location_id, description from t_location with (nolock)')
data = cursor.fetchall()
data_df = pd.DataFrame(data)

cursor.close()

关于python - 将 Python 连接到远程 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66753677/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com