PYnative

Python Programming

  • Learn Python ▼
    • Python Tutorials
    • Python Basics
    • Python Interview Q&As
  • Exercises ▼
    • Python Exercises
    • C++ Exercises
    • C Programming Exercises
    • Java Exercises
    • C# Exercises
  • Quizzes
  • Online Compilers▼
    • Online Python Code Editor
    • Online C Compiler
    • Online C++ Compiler
    • Online Java Compiler
    • Online C# Compiler
Home » Python » Databases » Insert / Retrieve file and images as a Blob in MySQL using Python

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

Updated on: March 9, 2021 | 38 Comments

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 BLOB data files from the MySQL table in Python

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

Further Reading:

  • Solve Python MySQL Exercise
  • Read Python MySQL Tutorial (Complete Guide)

Table of contents

  • Prerequisites
  • What is BLOB
  • Insert Image and File as a BLOB data into MySQL Table
  • Retrieve Image and File stored as a BLOB from MySQL Table using Python
  • Next Steps:

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.
mysql table with blob columns
Python MySQL table with blob columns

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.

import mysql.connector

def convertToBinaryData(filename):
    # 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")
Code language: Python (python)

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.

mysql table after inserting BLOB data from Python
MySQL table after inserting BLOB data from Python

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.
import mysql.connector


def write_file(data, filename):
    # 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")
Code language: Python (python)

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.

image and file stored on disk after reading BLOB data from mysql
image and file 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 to Practice and master the Python Database operations.

Filed Under: Python, Python Databases

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

I’m Vishal Hule, the Founder of PYnative.com. As a Python developer, I enjoy assisting students, developers, and learners. Follow me on Twitter.

Related Tutorial Topics:

Python Python Databases

All Coding Exercises:

C Exercises
C++ Exercises
Python Exercises
Java Exercises
C# Exercises

Python Exercises and Quizzes

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

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 25+ questions
  • Each Quiz contains 25 MCQ
Exercises
Quizzes

Comments

  1. Luciano C. says

    October 4, 2023 at 10:05 pm

    THANK YOU VERY MUCH, YOU SAVE MY LIFE.

    Reply
  2. deepak kumar nahta says

    October 18, 2022 at 12:54 am

    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’

    Reply
    • xcoder says

      May 28, 2026 at 1:51 pm

      create root path for that file then it will works.

      Reply
  3. Nayaki says

    January 19, 2022 at 1:26 am

    Sir, What is the code for displaying mysql database images on our website? Could you please help me with this?

    Reply
  4. Priyanka says

    December 7, 2021 at 11:49 pm

    Hi,
    Can we pass zip file to blob? N how?

    Reply
  5. faizal says

    November 3, 2020 at 9:22 am

    Can I pass the variable values instead of hard-coded?

    Reply
  6. Sarathkumar says

    September 24, 2020 at 11:38 am

    How to insert image file using post method in MySQL workbench , I have error pls tell me a suggestion to rectify sn error

    Reply
  7. Bahati says

    June 27, 2020 at 6:15 am

    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.

    Reply
  8. Ngawang says

    April 23, 2020 at 2:56 pm

    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

    Reply
    • Vishal says

      April 23, 2020 at 7:48 pm

      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

      Reply
      • Sarathkumar says

        September 30, 2020 at 11:31 pm

        But I use long blob, but I won’t save the image in MySQL , only show the image name ,

        Reply
  9. Kanad says

    April 1, 2020 at 9:58 am

    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:

    sql_fetch_blob_query = """SELECT * from python_employee where id = %s"""
    Reply
    • Vishal says

      April 1, 2020 at 3:46 pm

      Thank you, Kanad for your observation. I have updated the example.

      Reply
  10. ismail says

    March 20, 2020 at 4:12 pm

    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

    Reply
    • Vishal says

      March 20, 2020 at 6:51 pm

      Hey Ismail, Please let me know if you are getting any exceptions. or please post your code

      Reply
  11. rakesh sahoo says

    March 8, 2020 at 2:29 pm

    What is of these 2 sql_insert_blob_query and insert_blob_tuple???

    Reply
  12. manjinder says

    November 18, 2019 at 11:20 pm

    Hi,
    how can i remove this error?
    TypeError: a bytes-like object is required, not ‘str’

    Reply
    • Vishal says

      November 19, 2019 at 12:09 pm

      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

      Reply
  13. CHERALA ALEKHYA . says

    October 23, 2019 at 11:29 am

    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?

    Reply
    • Vishal says

      October 24, 2019 at 2:12 pm

      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.

      Reply
  14. srinadh says

    August 23, 2019 at 5:41 pm

    I need help for python mysql where i want to insert a row from keyboard like prepared statement in java-mysql.

    Reply
    • Vishal says

      August 24, 2019 at 6:23 pm

      Hi Srinath, Please refer to https://pynative.com/python-mysql-execute-parameterized-query-using-prepared-statement/

      Reply
      • Yasir Nomani says

        August 8, 2020 at 6:39 am

        How to retrieve blob Data and render in a nice format and display images and biodata in another html after clicking the photo?

        Reply
  15. Alain says

    May 25, 2019 at 12:31 pm

    Hi,

    How did you pass your photo from front end html to back end? Is your photo here in this example a file?

    Thanks

    Reply
    • Vishal says

      May 28, 2019 at 6:55 am

      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.

      Reply
  16. Jincy mariam Johnson says

    March 26, 2019 at 8:54 pm

    def csv_file_datas(ids, file):
    try:
    conn = MySQLdb.connect(host=”localhost”, user=”root”, password=”root”, db=”pda”)
    c = conn.cursor()
    query = “””SELECT * from skillassessment_csvfiles where fileid_id = %s”””
    c.execute(query,(ids))
    records = c.fetchall()
    for row in records:
    new_file = row[2]
    print “Storing file on disk \n”
    with open(settings.MEDIA_ROOT + ‘temp_file/’ + file, ‘wb’) as file:
    new_data = file.write(new_file)
    conn.commit()
    conn.close()
    except Exception as e:
    print e
    

    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” ).

    Reply
  17. Jincy mariam Johnson says

    March 26, 2019 at 8:54 pm

    def csv_file_datas(ids, file):
    try:
    conn = MySQLdb.connect(host=”localhost”, user=”root”, password=”root”, db=”p_db”)
    c = conn.cursor()
    query = “””SELECT * from skillassessment_csvfiles where fileid_id = %s”””
    c.execute(query,(ids))
    records = c.fetchall()
    for row in records:
    new_file = row[2]
    print “Storing file on disk \n”
    with open(settings.MEDIA_ROOT + ‘temp_file/’ + file, ‘wb’) as file:
    new_data = file.write(new_file)
    conn.commit()
    conn.close()
    except Exception as e:
    print e, ‘errorsssss’
    
    Reply
    • Brajesh Kumar says

      February 26, 2020 at 1:07 am

      I want to learn python in basic ……….

      Reply
  18. Jincy mariam Johnson says

    March 26, 2019 at 8:51 pm

    I’m getting error ” ‘long’ objects is not iterable” while executing the file.

    Reply
    • Vishal says

      March 26, 2019 at 8:52 pm

      Hey Jincy, can you please paste the code you trying. also, check the type you are using to read file from DB

      Reply
  19. Daniel Duarte says

    March 23, 2019 at 8:25 pm

    What is the bioData file for?

    Reply
    • Vishal says

      March 23, 2019 at 11:30 pm

      Biodata file contains employee details in txt format

      Reply
  20. Anatoliy says

    February 28, 2019 at 8:12 pm

    HI,
    I’m just comment your solution.
    You gets a warning about truncated data if you put an image larger than 64k.

    Reply
    • Anatoliy says

      March 1, 2019 at 1:19 pm

      The proof link about BLOB field max length: https://mariadb.com/kb/en/library/blob/

      Reply
  21. Utkarsh Kore says

    January 28, 2019 at 2:21 am

    I’m getting error while reading the file
    UnucodeDecodeError: ‘utf-8’ codec can’t decode byte 0xff in position 0: invalid start type

    Reply
    • Vishal says

      January 28, 2019 at 8:55 am

      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

      Reply
      • Utkarsh Kore says

        January 28, 2019 at 10:39 pm

        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

        Reply
        • Darshan Patil says

          February 27, 2020 at 7:32 pm

          Stored image can not be opening . It’s shows “It appears that we don’t support this file format”.

          Reply

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your entire code </pre>

In: Python Python Databases
TweetF  sharein  shareP  Pin

  Python MySQL

  • Python MySQL Connection Guide
  • Python MySQL Insert
  • Python MySQL Select
  • Python MySQL Update
  • Python MySQL Delete
  • Call MySQL Stored Procedure
  • Python MySQL Parameterized Query
  • Python MySQL Transactions
  • Python MySQL Connection Pooling
  • Python MySQL BLOB
  • Python Database Exercise

 Explore Python

  • Python Tutorials
  • Python Exercises
  • Python Quizzes
  • Python Interview Q&A
  • Python Programs

All Python Topics

Python Basics Python Exercises Python Quizzes Python Interview Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Coding Exercises

  • C Exercises
  • C++ Exercises
  • Python Exercises
  • Java Exercises
  • C# Exercises

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our:

  • Terms Of Use
  • Privacy Policy
  • Cookie Policy

Copyright © 2018–2026 pynative.com