Created
January 11, 2022 21:48
-
-
Save wiverson/58071126c52b629ef2b5a9201acaf326 to your computer and use it in GitHub Desktop.
Images to SQLite Python Script
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #!/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