Movatterモバイル変換


[0]ホーム

URL:


Open In App
Next Article:
Retrieve Image and File stored as a BLOB from MySQL Table using Python
Next article icon

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: 

Python3
defconvertData(filename):# Convert images or files data to binary formatwithopen(filename,'rb')asfile:binary_data=file.read()returnbinary_data
  • Check Whether Database Connection is created or not using Python Program. Let's have a look in below code:
Python3
importmysql.connectorconnection=mysql.connector.connect(host='localhost',database='geeksforgeeks',user='root',password='shubhanshu')cursor=connection.cursor()ifconnectionisnotNone: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:

Python3
importmysql.connector# Convert images or files data to binary formatdefconvert_data(file_name):withopen(file_name,'rb')asfile:binary_data=file.read()returnbinary_datatry:connection=mysql.connector.connect(host='localhost',database='geeksforgeeks',user='root',password='shubhanshu')cursor=connection.cursor()# create table querycreate_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 firstcursor.execute(create_table)# printing successful messageprint("Table created Successfully")query=""" INSERT INTO demo(id, name, profile_pic, imp_files)\    VALUES (%s,%s,%s,%s)"""# First Data Insertionstudent_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 formatresult=cursor.execute(query,(student_id,student_name,first_profile_picture,first_text_file))# Committing the dataconnection.commit()print("Successfully Inserted Values")# Print error if occurredexceptmysql.connector.Erroraserror:print(format(error))finally:# Closing all resourcesifconnection.is_connected():cursor.close()connection.close()print("MySQL connection is closed")

Output:

The table formed in MySQL:

Explanation:

  • Establishing the connection with MySQL database.
  • Write the create table Query and Using cursor object, Executing it.
  • Now, Insert data into a table using SQL query and stored inqueryvariable.
  • Storing the data in variables such asstudent_id = "1",  Student_name = "Shubham" and for images or files, first we areconverting those files into binary dataand then stored into a variables.
  • Using cursor object, Executing the query. Inserting the data in the database in tuple format.
  • Using commit() method, We are saving the data.
  • After completing all operations, we have to close all the resources such as the connection and cursor object.

Click here to downloadPNG file andTXT file

Video Demonstration:


Improve
Article Tags :
Practice Tags :

Similar Reads

We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood ourCookie Policy &Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences

[8]ページ先頭

©2009-2025 Movatter.jp