如何使用Python在 SQLite 中插入图像?
在本文中,我们将讨论如何使用Python的sqlite3模块在 SQLite 中插入图像。
执行:
1. 使用Python代码设置与 SQLite 数据库的连接。
sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')
cursor = sqliteConnection.cursor()
2. 我们需要定义一个INSERT 查询来将BLOB 数据插入到表中。
sqlite_insert_blob_query = """ INSERT INTO Student
(name, img) VALUES (?, ?)"""
3. 通过调用这个convertToBinaryData()函数将人类可读的文件转换为二进制数据,并将其存储为empPhoto变量,
empPhoto = convertToBinaryData(photo)
4.一旦文件转换成二进制格式,现在让我们将数据转换成元组格式,
data_tuple = (name, empPhoto)
5. 使用cursor.execute()在Python执行SELECT 查询。
cursor = sqliteConnection.cursor()
cursor.execute(sqlite_insert_blob_query, data_tuple)
6. 使用sqliteConnection.commit()保存我们所做的更改。
sqliteConnection.commit()
7. 创建一个函数,将人类可读数据转换为二进制格式,以便将其存储到数据库中。
def convertToBinaryData(filename):
# Convert binary format to images or files data
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
8.关闭游标连接和MySQL数据库。
if sqliteConnection:
sqliteConnection.close()
print("the sqlite connection is closed")
下面是实现。
Python3
import sqlite3
# Function for Convert Binary Data
# to Human Readable Format
def convertToBinaryData(filename):
# Convert binary format to images
# or files data
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
def insertBLOB(name, photo):
try:
# Using connect method for establishing
# a connection
sqliteConnection = sqlite3.connect('SQLite_Retrieving_data.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
# insert query
sqlite_insert_blob_query = """ INSERT INTO Student
(name, img) VALUES (?, ?)"""
# Converting human readable file into
# binary data
empPhoto = convertToBinaryData(photo)
# Convert data into tuple format
data_tuple = (name, empPhoto)
# using cursor object executing our query
cursor.execute(sqlite_insert_blob_query, data_tuple)
sqliteConnection.commit()
print("Image and file inserted successfully as a BLOB into a table")
cursor.close()
except sqlite3.Error as error:
print("Failed to insert blob data into sqlite table", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("the sqlite connection is closed")
insertBLOB("Smith", "D:\Internship Tasks\GFG\images\One.png")
insertBLOB("David", "D:\Internship Tasks\GFG\images\person.png")
输出:
让我们使用带有正确格式命令的SELECT查询检查数据库中的输出,