Current Code:
import mysql.connector
import sys
def write_file(data, filename):
with open(filename, 'wb') as f:
f.write(data)
sampleNum = 0;
# select photo column of a specific author
# read database configuration
db_config = mysql.connector.connect(user='root', password='test',
host='localhost',
database='technical')
# query blob data form the authors table
cursor = db_config.cursor()
try:
sampleNum=sampleNum+1;
query = "SELECT file FROM test WHERE id=%s"
cursor.execute(query,(sampleNum,))
photo = cursor.fetchone()[0]
write_file(photo, 'User'+str(sampleNum)+'.jpg')
except AttributeError as e:
print(e)
finally:
cursor.close()
Goal of above code
Code above allows me to get the image from MySQL that is stored as a BLOB
and save it into a folder where .py
script is saved.
It works fine!
Similar code with .docx
import mysql.connector
import sys
def write_file(data, filename):
with open(filename, 'wb') as f:
f.write(data)
sampleNum = 0;
db_config = mysql.connector.connect(user='root', password='test',
host='localhost',
database='technical')
cursor = db_config.cursor()
try:
sampleNum=sampleNum+1;
query = "SELECT fileAttachment FROM document_control WHERE id=%s"
cursor.execute(query,(sampleNum,))
file = cursor.fetchone()[0]
write_file(file, 'User'+str(sampleNum)+'.docx')
except AttributeError as e:
print(e)
finally:
cursor.close()
Here I am trying to extract and save a docx file from MySQL stored as a BLOB
and it does not work.
The output of above script is the following:
f.write(data)
TypeError: a bytes-like object is required, not 'str'
How can I extract the .docx file from MySQL?
As per the insert query you mentioned
insert into document_control (fileattachment) values ('C:/Users/<user>/Desktop/Weekly Checks.xlsx');
it seems that you are just inserting the filepath in the database.
You must use LOAD_FILE to insert the actual file in the database blob object. How to use LOAD_FILE to load a file into a MySQL blob?
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.