Skip to content

Instantly share code, notes, and snippets.

@wiverson
Created January 11, 2022 21:48
Show Gist options
  • Select an option

  • Save wiverson/58071126c52b629ef2b5a9201acaf326 to your computer and use it in GitHub Desktop.

Select an option

Save wiverson/58071126c52b629ef2b5a9201acaf326 to your computer and use it in GitHub Desktop.
Images to SQLite Python Script
#!/usr/bin/env python3
import sqlite3
import os.path
# Convert file to blob data
def convertToBinaryData(filename):
with open(filename, 'rb') as file:
blobData = file.read()
return blobData
def insertBLOB(name, photo):
try:
sqliteConnection = sqlite3.connect('test.db')
cursor = sqliteConnection.cursor()
print("Connected to SQLite")
sqlite_insert_blob_query = """INSERT INTO Images (name, img) VALUES (?, ?)"""
empPhoto = convertToBinaryData(photo)
# Convert data into tuple format
data_record = (name, empPhoto)
# using cursor object executing our query
cursor.execute(sqlite_insert_blob_query, data_record)
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("SQLite connection closed")
# Set the directory you want to start from
rootDir = './images/'
for dirName, subdirList, fileList in os.walk(rootDir):
print('Found directory: %s' % dirName)
for name in fileList:
if name.lower().endswith('.png'):
print(os.path.join(dirName, name))
insertBLOB(name.removesuffix('.png'), os.path.join(dirName, name))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment