Open In App

Working with MySQL BLOB in Python

In Python Programming, We can connect with several databases like MySQL, Oracle, SQLite, etc., using inbuilt support. We have separate modules for each database. We can use SQL Language as a mediator between the python program and database. We will write all queries in our python program and send those commands to the database. So, Using these programs, we can perform several operations such as Insertion, Deletion, Updating, and Retrieving.

Here, In this article, We will discuss working with MySQL BLOB in python. With the help of BLOB(Large Binary Object) data type in MySQL, we can store files or images in our database in binary format.



Installation of MySQL Connector:

This connector will connect our python program to database. Just run this command,

Command:

pip install mysql-connector-python

Important steps for Python Database Programming:

import mysql.connector

connection = mysql.connector.connect(host=’localhost’, database='<database_name>’, user='<User_name>’, password='<password>’)



cursor = connection.cursor()
cursor.execute("select * from table_name")
cursor.close()
con.close()

We are done with the basic steps of connection. Now, Let’s discuss the main agenda of this article which is the practical implementation of BLOB data type in MySQL Python, 

create database geeksforgeeks;

For Example: 




def convertData(filename):
   
    # Convert images or files data to binary format
    with open(filename, 'rb') as file:
        binary_data = file.read()
     
    return binary_data




import mysql.connector
 
 
connection = mysql.connector.connect(
    host='localhost', database='geeksforgeeks',
    user='root', password='shubhanshu')
 
cursor = connection.cursor()
 
if connection is not None:
    print('Connected Successfully')
else:
    print('Connection Failed')

We are done with all basic which is required. Let’s see the complete code for inserting the images or files in the MySQL database using Python Programs:




import mysql.connector
 
 
# Convert images or files data to binary format
def convert_data(file_name):
    with open(file_name, 'rb') as file:
        binary_data = file.read()
    return binary_data
 
 
try:
    connection = mysql.connector.connect(host='localhost',
                                         database='geeksforgeeks',
                                         user='root',
                                         password='shubhanshu')
    cursor = connection.cursor()
    # create table query
    create_table = """CREATE TABLE demo(id INT PRIMARY KEY,\
    name VARCHAR (255) NOT NULL, profile_pic BLOB NOT NULL, \
    imp_files BLOB NOT NULL) """
 
    # Execute the create_table query first
    cursor.execute(create_table)
    # printing successful message
    print("Table created Successfully")
 
    query = """ INSERT INTO demo(id, name, profile_pic, imp_files)\
    VALUES (%s,%s,%s,%s)"""
 
    # First Data Insertion
    student_id = "1"
    student_name = "Shubham"
    first_profile_picture = convert_data("D:\GFG\images\shubham.png")
    first_text_file = convert_data('D:\GFG\details1.txt')
 
    # Inserting the data in database in tuple format
    result = cursor.execute(
        query, (student_id, student_name, first_profile_picture, first_text_file))
    # Committing the data
    connection.commit()
    print("Successfully Inserted Values")
 
# Print error if occurred
except mysql.connector.Error as error:
    print(format(error))
 
finally:
   
    # Closing all resources
    if connection.is_connected():
       
        cursor.close()
        connection.close()
        print("MySQL connection is closed")

Output:

The table formed in MySQL:

Explanation:

Click here to download PNG file and TXT file

Video Demonstration:


Article Tags :