gpt4 book ai didi

python - pymssql批量插入错误(python)

转载 作者:太空宇宙 更新时间:2023-11-03 16:45:22 24 4
gpt4 key购买 nike

尝试使用 pymssql 批量插入 CSV 文件,代码如下:

conn = pymssql.connect(host='server', user='user', password='secret', database='My_Dev')
cur = conn.cursor()
load = 'BULK INSERT TempStaging FROM \'/home/dross/python/scripts/var/csv/' + f + '.csv\' WITH (FIRSTROW = 1,FIELDTERMINATOR = ',',ROWTERMINATOR = \'\\n\') GO")'
cur.execute(load)

执行时出现以下错误:

Traceback (most recent call last):
File "./uploadResults.py", line 46, in <module>
cur.execute(sweepload)
File "pymssql.pyx", line 447, in pymssql.Cursor.execute (pymssql.c:7092)
File "_mssql.pyx", line 1009, in _mssql.MSSQLConnection.execute_query (_mssql.c:11585)
File "_mssql.pyx", line 1040, in _mssql.MSSQLConnection.execute_query (_mssql.c:11459)
File "_mssql.pyx", line 1160, in _mssql.MSSQLConnection.format_and_run_query (_mssql.c:12652)
File "_mssql.pyx", line 203, in _mssql.ensure_bytes (_mssql.c:2733)
AttributeError: 'tuple' object has no attribute 'encode'

第 46 行是 cur.execute 行

最佳答案

请注意,.format() 可能允许 sql injection ,但如果您控制文件名,那么它还不错(不确定参数在这里是否有效)。

另外,在处理 SQL 时你应该使用三引号字符串,你的生活会好得多。像这样:

load = '''BULK INSERT TempStaging FROM /home/dross/python/scripts/var/csv/{}.csv WITH (FIRSTROW=1, FIELDTERMINATOR=',', ROWTERMINATOR='\n')'''.format(filename)

使用三重引号,您还可以将其分解以使其更易于阅读:

load = '''
BULK INSERT TempStaging
FROM /home/dross/python/scripts/var/csv/{}.csv
WITH (
FIRSTROW=1
, FIELDTERMINATOR=','
, ROWTERMINATOR='\n'
)
'''.format(filename)

关于python - pymssql批量插入错误(python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36360301/

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