Pertama, pastikan Anda menggunakan with open(..)
untuk membaca file (contoh lain ). Ini secara otomatis menutup objek file ketika mereka habis atau pengecualian dimunculkan.
# common vars
connection = pyodbc.connect(...)
filename = 'Test.ics'
insert = 'insert into documents (name, documentType, document, customerNumber)'
# without hex encode
with open(filename, 'rb'):
bindata = f.read()
# with hex encode
with open(filename, 'rb'):
hexdata = f.read().encode('hex')
# build parameters
binparams = ('test200.ics', 'text/calendar', pyodbc.Binary(bindata), 1717)
hexparams = ('test200.ics', 'text/calendar', pyodbc.Binary(hexdata), 1717)
# insert binary
connection.cursor().execute(insert, binparams)
connection.commit()
# insert hex
connection.cursor().execute(insert, hexparams)
connection.commit()
# print documents
rows = connection.cursor().execute('select * from documents').fetchall()
for row in rows:
try:
# this will decode hex data we inserted
print str(row.document).decode('hex')
# attempting to hex decode binary data throws TypeError
except TypeError:
print str(row.document)
Saya kira Anda mendapatkan 0x343234353...
data dengan melihat hasil di Management Studio:
Ini tidak berarti data disimpan dengan cara ini, ini hanya cara Management Studio merepresentasikan image
, text
, ntext
, varbinary
, dll. tipe data di panel hasil.