Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 546
Sarge Avatar asked Sep 09 '13 12:09

Sarge


1 Answers

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.

like image 151
Bryan Avatar answered Oct 11 '22 03:10

Bryan