The first argument to execute must be a string or unicode query

你说的曾经没有我的故事 提交于 2019-12-22 08:46:38

问题


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.

The code is

file = pyodbc.Binary(open("some_pdf_file.pdf", "r").read())

cur.execute("INSERT INTO BlobDataForPDF(ObjectID, FileData, Extension) VALUES ('1', " + file + ", '.PDF')")
cur.commit()

The first argument, ObjectID, is sent as a string. I don't see any problem but am I missing something?


回答1:


Use parameterized insert:

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()

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.



来源:https://stackoverflow.com/questions/18698664/the-first-argument-to-execute-must-be-a-string-or-unicode-query

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!