要执行的第一个参数必须是字符串或Unicode查询 [英] The first argument to execute must be a string or unicode query
问题描述
我正在尝试使用pyodbc将blob数据上传到ms-sql db.并且我得到要执行的第一个参数必须是字符串或Unicode查询" 错误.
I am trying to upload a blob data to ms-sql db, using pyodbc. And I get "the first argument to execute must be a string or unicode query" error.
代码是
file = pyodbc.Binary(open("some_pdf_file.pdf", "r").read())
cur.execute("INSERT INTO BlobDataForPDF(ObjectID, FileData, Extension) VALUES ('1', " + file + ", '.PDF')")
cur.commit()
第一个参数ObjectID作为字符串发送.我没看到任何问题,但是我有什么遗漏吗?
The first argument, ObjectID, is sent as a string. I don't see any problem but am I missing something?
推荐答案
使用参数化插入:
file = pyodbc.Binary(open("some_pdf_file.pdf", "r").read())
sql = "insert into BlobDataForPDF(ObjectID, FileData, Extension) values (?, ?, ?)"
cur.execute(sql, ('1', file, '.PDF'))
cur.commit()
当前代码正在尝试将二进制数据与您的插入字符串连接在一起.使用参数可以将SQL字符串与插入的值隔离开,从而防止SQL注入,并且如果您多次使用不同的值执行插入操作,则效率更高.用法示例此处.
The current code is attempting to concatenate binary data with your insert string. Using parameters isolates your SQL string from the inserted values, protecting against SQL injection and is more efficient if you execute the insert multiple times with different values. Sample usage here.
这篇关于要执行的第一个参数必须是字符串或Unicode查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!