Tutorials  Articles  Notifications  Login  Signup


RK

Rajan Kumar

Founder at HackersFriend April 3, 2020, 10:18 p.m. ⋅ 6875 views

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

 



HackerFriend Logo

Join the community of 1 Lakh+ Developers

Create a free account and get access to tutorials, jobs, hackathons, developer events and neatly written articles.


Create a free account