0

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?

Eduards
  • 1,734
  • 2
  • 12
  • 37
  • What does `type(file)` give with `.docx`? Also can you please post some initial characters of variable `file` in the second script – Raj Dec 20 '19 at 11:30
  • Got it - here it is: `C:/Users//Desktop/Weekly Checks.xlsx` – Eduards Dec 20 '19 at 11:45
  • Are you using `blob` to save the file in the database or are you just saving the path to the file? – Raj Dec 20 '19 at 11:47
  • Just as blob - We need to use blob.. cannot be using file paths. This is the query from MySQL: `insert into document_control (fileattachment) values ('C:/Users//Desktop/Weekly Checks.xlsx');` – Eduards Dec 20 '19 at 11:48

1 Answers1

1

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?

Raj
  • 664
  • 4
  • 16