In this lesson, you will learn how to insert or save any digital information such as a file, image, video, or song as blob data into a MySQL table from Python. We will also learn how to fetch the file, image, video, or song stored in MySQL using Python.
Goals of this article
- Insert binary data into a MySQL table using Python
- Read
BLOBdata files from the MySQL table in Python
Note: We are using the MySQL Connector Python module to connect MySQL.
Further Reading:
Table of contents
Prerequisites
To Store BLOB data in a MySQL table, we need to create a table containing binary data. Alternatively, if you have a table, then modify it by adding one extra column with BLOB as its data type.
You can use the following query to create a table with a BLOB column.
CREATE TABLE `Python_Employee` ( `id` INT NOT NULL , `name` TEXT NOT NULL , `photo` BLOB NOT NULL , `biodata` BLOB NOT NULL , PRIMARY KEY (`id`))Code language: Python (python)
This table contains the following two BLOB columns.
- Photo: To store an employee picture.
- Biodata file: To store employee details in file format.

As of now, The python_employee the table is empty. Let’s insert employees’ photos and bio-data files in it. Before executing the following programs, please make sure you have the Username and password to connect MySQL.
What is BLOB
A BLOB (large binary object) is a MySQL data type used to store binary data. We can convert our files and images into binary data in Python and keep them in the MySQL table using BLOB.
Note: To insert a file or image into the MySQL table, we need to create a BLOB column as a type. MySQL has the following four BLOB types. Each holds a variable amount of data.
- TINYBLOB
- BLOB
- MEDIUMBLOB
- LONGBLOB
Above BLOB types differ only in the maximum length of the values they can hold. To read more on BLOB, you can visit this MySQL BLOB document.
Insert Image and File as a BLOB data into MySQL Table
Let’s insert employee photo and bio-data into a python_employee table. To insert BLOB data into MySQL Table from Python, you need to follow these simple steps: –
- Install MySQL Connector Python using Pip.
- Second, Establish MySQL database connection in Python.
- Create a function that can convert images and file into binary data.
- Then, Define the Insert query to enter binary data into the database table. All you need to know is the table’s column details.
- Execute the INSERT query using a
cursor.execute(). It returns the number of rows affected. - After the successful execution of the query, commit your changes to the database.
- Close the Cursor and MySQL database connection.
- Most important, Catch SQL exceptions, if any.
- At last, verify the result by selecting data from the MySQL table.
Let see the example now.
Output:
Inserting BLOB into python_employee table Image and file inserted successfully as a BLOB into python_employee table None MySQL connection is closed Inserting BLOB into python_employee table
Let’s have a look at python_employee table after inserting the image and file into it.

Note: We inserted employee id, name, photo, and bio-data file. For image and bio-data, we passed the location where it is present.
As you can see, we converted our image and file into a binary format by reading the image and file in the rb mode before inserting it into a BLOB column.
Also, we used a parameterized query to insert dynamic data into a MySQL table.
Retrieve Image and File stored as a BLOB from MySQL Table using Python
Suppose we want to read the file or images stored in the MySQL table in binary format and write that file back to some arbitrary location on the hard drive. Let see how we can do that.
- Read employee image, and file from MySQL table stored as a BLOB.
- Write this BLOB binary data on a disk. We can pass the file format we want it to display to write this binary data on a hard disk.
To read BLOB data from MySQL Table using Python, you need to follow these simple steps: –
- Install MySQL Connector Python using pip.
- Second, Establish MySQL database connection in Python.
- Then, Define the SELECT query to fetch BLOB column values from the database table.
- Execute the SELECT query using
cursor.execute() - Use
cursor.fetchall()to retrieve all the rows from the result set and iterate over it. - Create a function to write BLOB or binary data that we retrieved from each row on disk in a correct format.
- Close the Cursor and MySQL database connection.
Output:
Reading BLOB data from python_employee table Id = 1 Name = Eric Storing employee image and bio-data on disk MySQL connection is closed Reading BLOB data from python_employee table Id = 2 Name = Scott Storing employee image and bio-data on disk MySQL connection is closed
Retrieved image and file from MySQL table and stored on disk.

Next Steps:
To practice what you learned in this article, Please solve a Python Database Exercise project to Practice and master the Python Database operations.

THANK YOU VERY MUCH, YOU SAVE MY LIFE.
hi
vishal, I send you the function code and error message
please give me a solution if possible
def write_file():# Convert binary data to the proper format and write it on Hard Disk
with open("c:\dkphoto.jpg", 'wb') as file:
file.write("c:\imagile.jpg")
following error
File “C:\Users\Dell\PycharmProjects\Pycham\db.py”, line 145, in
write_file()
File “C:\Users\Dell\PycharmProjects\Pycham\db.py”, line 29, in write_file
with open(“c:\dkphoto.jpg”, ‘wb’) as file:
PermissionError: [Errno 13] Permission denied: ‘c:\\dkphoto.jpg’
create root path for that file then it will works.
Sir, What is the code for displaying mysql database images on our website? Could you please help me with this?
Hi,
Can we pass zip file to blob? N how?
Can I pass the variable values instead of hard-coded?
How to insert image file using post method in MySQL workbench , I have error pls tell me a suggestion to rectify sn error
thinks for this knowledge §
Now, how can i display image in label tkinter after save it on mysql database.
The image who is captured by openCV.
thanks again for your help.
Hello Vishal!
I am getting this error while inserting an image.
Inserting BLOB into python_employee table
Failed to insert BLOB data into MySQL table 1406 (22001): Data too long for column ‘photo’ at row 1
MySQL connection is closed
Hey Ngawang,
It all depends on the column type used for the photo column. Depending on your needs. BLOB can only store up to 65,535 bytes. Use MEDIUMBLOB to store larger data.
TINYBLOB: maximum length of 255 bytes
BLOB: maximum length of 65,535 bytes
MEDIUMBLOB: maximum length of 16,777,215 bytes
LONGBLOB: maximum length of 4,294,967,295 bytes
But I use long blob, but I won’t save the image in MySQL , only show the image name ,
Hi Vishal,
There is an error in the code in the “Retrieve Image and File stored as a BLOB from MySQL Table”;
It should have been
*instead of photo:Thank you, Kanad for your observation. I have updated the example.
that’s not working
all I get is Process finished with exit code 0
but when I check my DB I don’t see any changes
Hey Ismail, Please let me know if you are getting any exceptions. or please post your code
What is of these 2 sql_insert_blob_query and insert_blob_tuple???
Hi,
how can i remove this error?
TypeError: a bytes-like object is required, not ‘str’
Can you please refer to this
https://stackoverflow.com/questions/33054527/typeerror-a-bytes-like-object-is-required-not-str-when-writing-to-a-file-in
Hi, for each record you are giving the path but I have thounsands of records. How should I give path dynamically for all of them?
Hi CHERALA ALEKHYA,
you need to create a sperate function in which you can generate a dynamic path and pass that path to Insert function.
I need help for python mysql where i want to insert a row from keyboard like prepared statement in java-mysql.
Hi Srinath, Please refer to https://pynative.com/python-mysql-execute-parameterized-query-using-prepared-statement/
How to retrieve blob Data and render in a nice format and display images and biodata in another html after clicking the photo?
Hi,
How did you pass your photo from front end html to back end? Is your photo here in this example a file?
Thanks
Hi Alain,
we have not passed file from front end. we created a simple example by passing file path of a png image. if you want to pass file from front-end You have to use web framework.
This is my code. Actually, this code is working fine in localhost.
But in AWS shows an error that I mentioned earlier (” ‘long’ objects is not iterable” ).
I want to learn python in basic ……….
I’m getting error ” ‘long’ objects is not iterable” while executing the file.
Hey Jincy, can you please paste the code you trying. also, check the type you are using to read file from DB
What is the bioData file for?
Biodata file contains employee details in txt format
HI,
I’m just comment your solution.
You gets a warning about truncated data if you put an image larger than 64k.
The proof link about BLOB field max length: https://mariadb.com/kb/en/library/blob/
I’m getting error while reading the file
UnucodeDecodeError: ‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start type
Hey utakrsh, It seems that you are facing Unicode decode error. please refer to this https://stackoverflow.com/questions/42339876/error-unicodedecodeerror-utf-8-codec-cant-decode-byte-0xff-in-position-0-in
Yeah I tried those solutions but it didn’t work for me. Still getting the same error. I’ve stored my column as longblob datatype, if this has something related to error. Please help me with this
Stored image can not be opening . It’s shows “It appears that we don’t support this file format”.