Sunteți pe pagina 1din 8

5/12/2020 Python MySQL- Insert / Retrieve file and images as a Blob in MySQL

 Tutorials

Insert / Retrieve file and images as a Blob in MySQL using Python


PYnative
 Python Exercises(https://pynativ
 Python Quizze
 Code Editor(https://pynative.com/online-pytho
Last updated on April 26, 2020 |   Python Tricks(https://pynative.com/useful-python-tips-and-
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)

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.

Goals of this article

Insert binary data into a MySQL table using Python.

Read BLOB data les from the MySQL table in Python.

Note: We are using the MySQL Connector Python module to communicate with MySQL.

Further reading

Try to solve Python MySQL Exercise (https://pynative.com/python-database-programming-exercise-with-solution/)

Also, read Python MySQL Tutorial (Complete Guide) (https://pynative.com/python-mysql-tutorial/)

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 ,

This table contains the following two BLOB columns.

A photo which contains employee picture.

Biodata le which contains employee details in le format.

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

Python and store them in MySQL table using BLOB.

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)

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 (https://pynative.com/install-mysql-connector-python/).

Second, Establish MySQL database connection in Python (https://pynative.com/python-mysql-database-connection/).

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.

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.

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

# Convert digital data to binary format


with open(filename, 'rb') as file:
binaryData = file.read()
return binaryData

def insertBLOB(emp_id, name, photo, biodataFile):


print("Inserting BLOB into python_employee table")
try:
connection = mysql.connector.connect(host='localhost',
database='python_db',
user='pynative',
password='pynative@#29')

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)

# Convert data into tuple format


insert_blob_tuple = (emp_id, name, empPicture, file)
result = cursor.execute(sql_insert_blob_query, insert_blob_tuple)
connection.commit()
print("Image and file inserted successfully as a BLOB into python_employee table", result)

except mysql.connector.Error as error:


print("Failed inserting BLOB data into MySQL table {}".format(error))

finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")

insertBLOB(1, "Eric", "D:\Python\Articles\my_SQL\images\eric_photo.png",


"D:\Python\Articles\my_SQL\images\eric_bioData.txt")
insertBLOB(2, "Scott", "D:\Python\Articles\my_SQL\images\scott_photo.png",
"D:\Python\Articles\my_SQL\images\scott_bioData.txt")

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 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

mysql table after inserting BLOB data from Python

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.

Also, we used a parameterized query (https://pynative.com/python-mysql-execute-parameterized-query-using-prepared-


statement/) to insert dynamic data into a MySQL table.

Retrieve Image and File stored as a BLOB from MySQL Table

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.

Read employee image, and le from MySQL table stored as a BLOB.

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: –

Install MySQL Connector Python using pip (https://pynative.com/install-mysql-connector-python/).

Second, Establish MySQL database connection in Python (https://pynative.com/python-mysql-database-connection/).

Then, De ne the SELECT query to fetch BLOB columns 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.

import mysql.connector
from mysql.connector import Error

def write_file(data, filename):

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

# Convert binary data to proper format and write it on Hard Disk


with open(filename, 'wb') as file:
file.write(data)

def readBLOB(emp_id, photo, bioData):


print("Reading BLOB data from python_employee table")

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)

except mysql.connector.Error as error:


print("Failed to read BLOB data from MySQL table {}".format(error))

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:

Reading BLOB data from python_employee table


Id = 1
Name = Eric
Storing employee image and bio-data on disk

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

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 le from MySQL table and stored on disk.

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!

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

15+ Topic-speci c Exercises and Quizzes  Show All Exercises


Each Exercise contains 10 questions (https://pynative.com/python-exercises-with-solutions/)

Each Quiz contains 12-15 MCQ


 Sh All Q i

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/)

Is this article/website helpful?

Keep Reading Python


Python Input & Output (https://pynative.com/python-input-function-get-user-input/) Python MySQL (https://pynative.com/python-mysql-tutorial/)
Python PostgreSQL (https://pynative.com/python-postgresql-tutorial/) Python SQLite (https://pynative.com/python-sqlite/)
Python JSON (https://pynative.com/python-json/) Python Quizzes (https://pynative.com/python-quizzes/)
Python Exercises (https://pynative.com/python-exercises-with-solutions/)
Python Generate random data (https://pynative.com/python-random-module/)

 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/)

RSS (https://pynative.com/feed/) | Sitemap (https://pynative.com/sitemap.xml)

Twitter Facebook

(https://twitter.com/PyNative)   (https://www.facebook.com/PyNative-209205313026120/)

Python
Python Tutorials (https://pynative.com/python-tutorials/)

Python Exercises (https://pynative.com/python-exercises-with-solutions/)

Python Quizzes (https://pynative.com/python-quizzes/)

Online Python Code Editor (https://pynative.com/online-python-code-editor-to-execute-python-code/)

Python Tricks (https://pynative.com/useful-python-tips-and-tricks-every-programmer-should-know/)

Join Our Newsletter


Subscribe and Get New Python Tutorials, Exercises, Tips and Tricks into your Inbox Every alternate Week.

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/)

Cookie Policy (https://pynative.com/cookie-policy/)

Terms Of Use (https://pynative.com/terms-of-use/)

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/)

Copyright © 2018-2020 · [pynative.com]

AN ELITE CAFEMEDIA TECH PUBLISHER

https://pynative.com/python-mysql-blob-insert-retrieve-file-image-as-a-blob-in-mysql/ 8/8

S-ar putea să vă placă și