SQL Server 2017中的pyodbc连接

2024-05-03 23:57:28 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我在stackoverflow上的第一篇文章,如果我做错了什么,请容忍我

我目前正在尝试实现一个Python脚本,该脚本从CSV文件读取数据,将其转换为JSON对象,并将其存储在SQL Server表中。如果我直接在Python中执行此操作,那么一切都正常工作。我有一个完全工作的Python脚本,它可以读取CSV并通过SQL Server上的pyodbc存储数据

不幸的是,当我试图在sp_execute_external_script中使用类似的脚本时,我得到一个错误,即无法建立连接

我的T-SQL代码:

DECLARE @Python as nvarchar(max)

SET @Python = N'
import pyodbc

import datetime as datetime

conn_str = (
    r''DRIVER={ODBC Driver 17 for SQL Server};''
    r''SERVER=xxx.xxx.xxx.xxx;''
    r''DATABASE=xxxx;''
    r''UID=xxxxxx;''
    r''PWD=xxxx;''
)

cnxn = pyodbc.connect(conn_str)
'

EXEC sp_execute_external_script
@language = N'Python',
@script = @Python ,
@input_data_1 = N'',
@input_data_1_name = N''

错误消息

Meldung 39004, Ebene 16, Status 20, Zeile 2 Unerwarteter "Python"-Skriptfehler beim Ausführen von "sp_execute_external_script" mit HRESULT 0x80004004. Meldung 39019, Ebene 16, Status 2, Zeile 2 Externer Skriptfehler:

Error in execution. Check the output for more information. Traceback (most recent call last): File "", line 5, in File "E:\Program Files\Microsoft SQL Server\MSSQL14.CWDEV\MSSQL\ExtensibilityData\CWDEV01\6F73A5E0-4F82-4FEA-A5DA-7A8E7D8778D2\sqlindb.py", line 53, in transform cnxn = pyodbc.connect(conn_str) pyodbc.Error: ('08001', '[08001] [Microsoft][ODBC Driver 17 for SQL Server]Named Pipes-Anbieter: Es konnte keine Verbindung zu SQL Server hergestellt werden [1326]. (1326) (SQLDriverConnect)')

SqlSatelliteCall error: Error in execution. Check the output for more information. STDOUT-Meldung(en) aus dem externen Skript: SqlSatelliteCall function failed. Please see the console output for more information. Traceback (most recent call last): File "E:\Program Files\Microsoft SQL Server\MSSQL14.CWDEV\PYTHON_SERVICES\lib\site-packages\revoscalepy\computecontext\RxInSqlServer.py", line 406, in rx_sql_satellite_call rx_native_call("SqlSatelliteCall", params) File "E:\Program Files\Microsoft SQL Server\MSSQL14.CWDEV\PYTHON_SERVICES\lib\site-packages\revoscalepy\RxSerializable.py", line 291, in rx_native_call ret = px_call(functionname, params) RuntimeError: revoscalepy function failed.

目前,我正在尝试连接到目标服务器。顺便说一句,代码没有在目标服务器上运行,它将在不同的服务器上执行。我的想法是在特定的SQL Server上使用sp_execute_external_script和Python将数据从平面文件中迁移出来,并将其存储在不同的目标SQL Server上

任何建议都将不胜感激

非常感谢


Tags: in脚本forexecutesqlserverlinescript