Documente Academic
Documente Profesional
Documente Cultură
Tutorials
F share (https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fpynative.com%2Fpython-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql%2F)
in share (https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fpynative.com%2Fpython-mysql-blob-insert-retrieve-file-image-as-a-blob-in-
mysql%2F&title=Insert+%2F+Retrieve+file+and+images+as+a+Blob+in+MySQL+using+Python)
P Pin (https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fpynative.com%2Fpython-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql%2F&media=https://pynative.com/wp-
content/uploads/2019/02/python_mysql_blob_data.png&description=Insert+%2F+Retrieve+file+and+images+as+a+Blob+in+MySQL+using+Python)
In this article, I will let you know how to insert or save any digital information such as a le, image, video, or a song as a blob data into MySQL
table from python. We will also learn how we can fetch the le, image, video, or a song stored in MySQL using Python.
Note: We are using the MySQL Connector Python module to communicate with MySQL.
Further reading
Prerequisites
To Store BLOB data in MySQL table, we need to create a table that can hold binary data. Alternatively, if you have a table then modify it and add
one extra column with BLOB as its data type.
You can use the following query to a create 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 ,
The python_employee table is empty as of now let’s insert employees’ photo and bio-data le in it. Before executing the following
programs, please make sure you have the Username and password that you need to connect MySQL.
What is BLOB
A BLOB (large binary object) is a MySQL data type that can be used to store binary data. We can convert our les and images into binary data in
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 1/8
5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL
Note: To insert le or image into MySQL table we need to create a column that has a BLOB as a type. MySQL has the following four BLOB types.
Each holds a variable amount of data.
TINYBLOB
BLOB
MEDIUMBLOB
LONGBLOB
Above BLOB types di er only in the maximum length of the values they can hold. To read more on BLOB you can visit this MySQL BLOB
document. (https://dev.mysql.com/doc/refman/8.0/en/blob.html)
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: –
Create a function that can convert image and le into binary data.
Then, De ne the Insert query to enter binary data into the database table. All you need to know is the table it’s column details.
Execute the INSERT query using cursor.execute(). In return, you should get some rows a ected.
After the successful execution of the query, commit your changes to the database.
At last, verify the result by selecting data from the MySQL table.
import mysql.connector
from mysql.connector import Error
def convertToBinaryData(filename):
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 2/8
5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL
cursor = connection.cursor()
sql_insert_blob_query = """ INSERT INTO python_employee
(id, name, photo, biodata) VALUES (%s,%s,%s,%s)"""
empPicture = convertToBinaryData(photo)
file = convertToBinaryData(biodataFile)
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
Output:
Let’s have a look at python_employee table after inserting the image and le into it.
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 3/8
5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL
Note: We inserted employee id, name, photo and bio-data le. For image and bio-data, we passed the location where it is present.
As you can see we converted our image and le into a binary format by reading image and le in ‘rb‘ mode before inserting it into a
BLOB column.
Suppose we want to read the le or images stored in MySQL table in binary format and write that le back to some arbitrary location on the
hard drive. Let see how we can do that.
Write this BLOB binary data on a disk. To write this binary data on hard disk we can pass the le format in which we want it to be displayed.
To read BLOB data from MySQL Table using Python, you need to follow these simple steps: –
Then, De ne the SELECT query to fetch BLOB columns values from the database table.
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.
import mysql.connector
from mysql.connector import Error
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 4/8
5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL
try:
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='pynative',
password='pynative@#29')
cursor = connection.cursor()
sql_fetch_blob_query = """SELECT * from python_employee where id = %s"""
cursor.execute(sql_fetch_blob_query, (emp_id,))
record = cursor.fetchall()
for row in record:
print("Id = ", row[0], )
print("Name = ", row[1])
image = row[2]
file = row[3]
print("Storing employee image and bio-data on disk \n")
write_file(image, photo)
write_file(file, bioData)
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
readBLOB(1, "D:\Python\Articles\my_SQL\query_output\eric_photo.png",
"D:\Python\Articles\my_SQL\query_output\eric_bioData.txt")
readBLOB(2, "D:\Python\Articles\my_SQL\query_output\scott_photo.png",
"D:\Python\Articles\my_SQL\query_output\scott_bioData.txt")
Output:
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 5/8
5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL
image and le stored on disk after reading BLOB data from mysql
Next Steps:
To practice what you learned in this article, Please solve a Python Database Exercise project (https://pynative.com/python-database-
programming-exercise-with-solution/) to Practice and master the Python Database operations.
Did you nd this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.
Tweet (https://twitter.com/intent/tweet/?text=Insert+%2F+Retrieve+file+and+images+as+a+Blob+in+MySQL+using+Python&url=https%3A%2F%2Fpynative.com%2Fpython-mysql-
blob-insert-retrieve-file-image-as-a-blob-in-mysql%2F&via=PyNative)
F share (https://facebook.com/sharer/sharer.php?u=https%3A%2F%2Fpynative.com%2Fpython-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql%2F)
in share (https://www.linkedin.com/shareArticle?mini=true&url=https%3A%2F%2Fpynative.com%2Fpython-mysql-blob-insert-retrieve-file-image-as-a-blob-in-
mysql%2F&title=Insert+%2F+Retrieve+file+and+images+as+a+Blob+in+MySQL+using+Python)
P Pin (https://pinterest.com/pin/create/button/?url=https%3A%2F%2Fpynative.com%2Fpython-mysql-blob-insert-retrieve-file-image-as-a-blob-in-
mysql%2F&media=https://pynative.com/wp-
content/uploads/2019/02/python_mysql_blob_data.png&description=Insert+%2F+Retrieve+file+and+images+as+a+Blob+in+MySQL+using+Python)
About Vishal
Founder of PYnative.com (https://pynative.com) I am a Python developer and I love to write articles to help developers.
Follow me on Twitter (https://twitter.com/PyNative). All the best for your future Python endeavors!
Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 6/8
5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL
Show All Quizzes
(https://pynative.com/python-quizzes/)
Comments
Thank you for reading. Leave a comment below and let us know what do you think of this article.
Follow PYnative
Home (https://pynative.com)
NewsLetter (https://pynative.com/newsletter/)
About Us (https://pynative.com/about-us/)
Twitter Facebook
(https://twitter.com/PyNative) (https://www.facebook.com/PyNative-209205313026120/)
Python
Python Tutorials (https://pynative.com/python-tutorials/)
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 7/8
5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL
Legal Stuff
Privacy Policy (https://pynative.com/privacy-policy/)
Contact Us (https://pynative.com/contact-us/)
(https://www.dmca.com/Protection/Status.aspx?ID=432bf555-858e-4ab8-bbe9-
165ce5351163&refurl=https://pynative.com/python-mysql-blob-insert-retrieve- le-image-as-a-blob-in-mysql/)
https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 8/8