How to upload file to SQL server using pyodbc python
To upload files to SQL server using pyodbc we use pyodbc.Binary() function. We open file as binary file using python open() function, and read it into a variable. Then we pass this to pyodbc.Binary() after that, we insert this value as varbinary in FileTable.
Here is how to implement it.
# Get connection
connection = pyodbc.connect(...)
filename = 'MyFile.pdf'
insert = 'insert into FileTable (name, document) values (?,?)'
# open file as binary and read into a variable
with open(filename, 'rb') as f:
bindata = f.read()
# build query
binparams = ('MyFile.pdf', pyodbc.Binary(bindata))
# insert binary
connection.cursor().execute(insert, binparams)
connection.commit()
connection.close()