【问题标题】:How do I properly send a BCP command in Python to a remote server?如何正确地将 Python 中的 BCP 命令发送到远程服务器?
【发布时间】:2021-04-11 08:54:21
【问题描述】:

我正在尝试使用 python 在远程服务器上运行 BCP 命令。我需要数据,以及每个表的 xml 格式文件。由于我的第一个表查询仍然失败,我还没有尝试格式化命令。

import pyodbc
import sys
import subprocess
import os
import bcp

conn = pyodbc.connect('Driver={SQL Server};'
                      'Server=10.100.100.10;'
                      'Database=CompanyDatabase;'
                      'Trusted_Connection=yes;')
cursor = conn.cursor()
command = 'bcp.exe CompanyDatabase.dbo.AnyTableName out D:\PROD\BCPLIST\CompanyDatabase_AnyTableName.csv -c -t "|C^|" -r "|R^|" -T -S 10.10.100.100.10'
cursor.execute(command)

执行上述脚本,总是会产生如下错误:

pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]'.' 附近的语法不正确。(102) (SQLExecDirectW)")

我可以在批处理脚本中发送命令并且它工作正常,但我的上级真的更喜欢我使用 python 来做这个。执行服务器和远程服务器在网络中是受信任的,因此省略了用户/密码参数。

以下工作批处理脚本循环通过表名的文本文件,为每个脚本运行以下命令。 %%x = 数据库中表的名称,带有行分隔符|R^|和列 |C^|

bcp.exe CompanyDatabase.dbo.%%x out D:\PROD\BCPLIST\CompanyDatabase_%%x.csv -c -t "|C^|" -r "|R^|" -T -S 10.100.100.10
bcp.exe CompanyDatabase.dbo.%%x format nul -c -x -f D:\PROD\BCPLIST\CompanyDatabaseFormat_%%x.xml -t "|C^|" -r "|R^|" -T -S 10.100.100.10

【问题讨论】:

  • bcp 是一个命令行工具,类似于curlpythonpipnano,不是 SQL 命令。你不能用cursor.execute 运行它。您可以在本地安装它并针对远程服务器运行它
  • they would really prefer i use python for this 谁是“他们”,为什么他们希望您使用 Python 来运行脚本命令而不是只运行脚本?您必须了解实际要求是什么。在某些事情奏效之前,您不能只是尝试。甚至The executing and remote servers are trusted within the network, 也是错误的——没有这样的事情。运行bcp帐户 是具有连接数据库权限的Active Directory 用户。这就是 Windows 身份验证起作用的原因
  • 他们是我的公司
  • 所以你看,问题不在于 Powershell。如果你使用 Python,它不会被修复。
  • 其实我说得太早了。我不得不重新添加正确的服务器 IP,它运行良好。谢谢先生。

标签: python sql-server bcp


【解决方案1】:

扩展 Panagiotis Kanavos 的评论; 通过使用 subprocess 包,您可以将整个 bcp 命令放入其中并绕过 bcp 实用程序。

import subprocess
datacommand = 'bcp.exe Databasename.dbo.databasetable out D:\DirectoryPath\Testbcp.csv -c -t "|C^|" -r "|R^|" -T -S 10.100.100.10'
subprocess.call(datacommand)
formatcommand = 'bcp.exe Databasename.dbo.databasetable format nul -c -x -f D:\DirectoryPath\Format.xml -t "|C^|" -r "|R^|" -T -S 10.100.100.10'
subprocess.call(formatcommand)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-05-17
    • 1970-01-01
    • 1970-01-01
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 2013-06-05
    相关资源
    最近更新 更多