Created
August 16, 2020 05:18
-
-
Save kshirsagarsiddharth/586068bf787b6bba4c2a34c7582bdbe8 to your computer and use it in GitHub Desktop.
Inserting files into database and retrieving them
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
| import sqlite3 | |
| def convert_to_binary(filename): | |
| with open(filename,'rb') as f: | |
| blob_data = f.read() | |
| return blob_data | |
| def insert_blob(id,name,photo,resume): | |
| try: | |
| sqlite_connection = sqlite3.connect('sqlite3_python_database.db') | |
| cursor = sqlite_connection.cursor() | |
| print("connection is sucessful") | |
| sqlite_insert_blob_query = """ | |
| INSERT INTO new_employee (id,name,photo,resume) VALUES (?,?,?,?); | |
| """ | |
| emp_photo = convert_to_binary(photo) | |
| resume_bin = convert_to_binary(resume) | |
| data_tuple = (id,name,emp_photo,resume_bin) | |
| cursor.execute(sqlite_insert_blob_query,data_tuple) | |
| sqlite_connection.commit() | |
| except sqlite3.Error as error: | |
| print("Failed to insert blob data into sqlite table",error) | |
| finally: | |
| if sqlite_connection: | |
| sqlite_connection.close() | |
| print("The connection to the database is closed") | |
| def write_to_file(data,filename): | |
| with open(filename,'wb') as f: | |
| f.write(data) | |
| print(f"BLOB written into {filename} \n") | |
| def read_blob(id): | |
| try: | |
| sqlite_connection = sqlite3.connect("sqlite3_python_database.db") | |
| cursor = sqlite_connection.cursor() | |
| print("The connection is sucessful") | |
| sqlite_fetch_blob_data = """ | |
| SELECT id,name,photo,resume | |
| FROM new_employee | |
| WHERE id = ?; | |
| """ | |
| cursor.execute(sqlite_fetch_blob_data,(id,)) | |
| record = cursor.fetchall() | |
| for row in record: | |
| print("ID = ",row[0]) | |
| print("name = ",row[1]) | |
| name = row[1] | |
| photo = row[2] | |
| resume = row[3] | |
| print("Storing employee image and resume on the disk \n") | |
| photo_path = f"D:\python_cookbook\sql\sqlite3_list\{name}.jpg" | |
| resume_path = f"D:\python_cookbook\sql\sqlite3_list\{name}.jpg" | |
| write_to_file(photo,photo_path) | |
| write_to_file(resume,resume_path) | |
| cursor.close() | |
| except sqlite3.Error as error: | |
| print("Failed to read blob",error) | |
| finally: | |
| if sqlite_connection: | |
| sqlite_connection.close() | |
| print("The connection to the database is closed") | |
| read_blob(1) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment