from sqlalchemy import create_engine
my_conn = create_engine("sqlite:///D:\\testing\\my_db\\my_db.db")
my_conn.execute('''
CREATE TABLE IF NOT EXISTS student(id integer primary key,
name text,
class text,
mark integer,
gender text,
photo blob
);''')
print("Student Table created successfully");
rb
: Read Binary
fob=open('G:\\My Drive\\testing\\my_db\\sqlite-blob1.jpg','rb')
blob_data=fob.read()
Along with other data we are storing binary data in our student table. We used try except error handling to display error messages.
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("sqlite:///D:\\testing\\my_db\\my_db.db")
fob=open('G:\\My Drive\\testing\\my_db\\sqlite-blob1.jpg','rb') #file object
blob_data=fob.read() # Binary data is ready
my_data=[(None, 'Tes Qry', 'Six', 78, 'male',blob_data)] # Data to store
q="INSERT INTO student values(?,?,?,?,?,?)" # query with place holders
try:
r_set=my_conn.execute(q,my_data)
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
print(error)
else:
print("Number of records added : ",r_set.rowcount)
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("sqlite:///D:\\testing\\my_db\\my_db.db")
q='''SELECT * FROM student WHERE id=37'''
my_cursor=my_conn.execute(q)
data_row=my_cursor.fetchone()
fob=open('G:\\My Drive\\testing\\my_db\\sqlite-blob2.jpg','wb')
fob.write(data_row[5]) # create the image using above path
While storing ( inserting to table ) the image in SQLite database we used file name sqlite-blob1.jpg. At the same location another file sqlite-blob2.jpg will be created to store the same. Change the file location if it is required to store the data in different location.
from PIL import Image
import io
In above code we use the data_row[5] which holds the binary data ( photo ).
image = Image.open(io.BytesIO(data_row[5]))
image.show()
Using matplotlib we can display the image in Google Colab console. image = Image.open(io.BytesIO(r_set[5]))
import matplotlib.pyplot as plt
plt.imshow(image)
plt.show()
from sqlalchemy import create_engine
from sqlalchemy.exc import SQLAlchemyError
my_conn = create_engine("sqlite:///D:\\testing\\my_db\\my_db.db")
fob=open('G:\\My Drive\\testing\\my_db\\sqlite-blob3.jpg','rb')
blob_data=fob.read()
my_data=(blob_data,37) # tuple to pass values to execute method
q="UPDATE student SET photo=? WHERE id=? "
try:
r_set=my_conn.execute(q,my_data)
except SQLAlchemyError as e:
error=str(e.__dict__['orig'])
print(error)
else:
print("Number of records Updated : ",r_set.rowcount)
my_data=(37) # tuple to pass values to execute method
q="UPDATE student SET photo='' WHERE id=? "
We can update the column to Null value.
my_data=(37) # tuple to pass values to execute method
q="UPDATE student set photo=NULL WHERE id=? "
!wget https://www.plus2net.com/python/download/1.png
!wget https://www.plus2net.com/python/download/2.png
!wget https://www.plus2net.com/python/download/3.png
!wget https://www.plus2net.com/python/download/4.png
import sqlite3 # Connection library
my_conn = sqlite3.connect('student_blob_2.db') # connect to db
try:
my_conn.execute('DROP table student_b') # Delete the table if required.
except sqlite3.Error as my_error:
print("error: ", my_error)
else:
print("Student Table Deleted")
try:
my_conn.execute('''
CREATE TABLE IF NOT EXISTS student_b(id integer primary key,
name text,
class text,
gender text,
photo blob
);''')
except sqlite3.Error as my_error:
print("error: ", my_error)
else:
print("Student Table created successfully")
from PIL import Image
import io
import matplotlib.pyplot as plt
query = "pragma table_info([student_b])"
my_data = list(my_conn.execute(query)) # structure
print(my_data) # Listing structure of table
my_students = [[1, 'Alex J', 'Four', 'Female', '1.png'],
[2, 'Ramana K', 'Three', 'Male', '2.png'],
[3, 'Jack', 'Five', 'Female', '3.png'],
[4, 'Ronne', 'Six', 'Female', '4.png']]
for ids in my_students:
fob = open(ids[4], 'rb') # file object
blob_data = fob.read() # Binary data is ready
my_data = (None, ids[1], ids[2], ids[3], blob_data) # Data to store
q = "INSERT INTO student_b values(?,?,?,?,?)" # query with place holders
try:
r_set = my_conn.execute(q, my_data)
except sqlite3.Error as my_error:
print("error: ", my_error)
else:
print("Number of records added : ", r_set.rowcount)
r_set = my_conn.execute('SELECT * from student_b ')
for row in r_set:
image = Image.open(io.BytesIO(row[4]))
plt.figure(figsize=(1, 1))
plt.axis(False)
plt.imshow(image)
print(row[0], row[1], row[2], row[3], '')
plt.show()
print()
from google.colab import files
files.download('student_blob_2.db')
Author
🎥 Join me live on YouTubePassionate about coding and teaching, I publish practical tutorials on PHP, Python, JavaScript, SQL, and web development. My goal is to make learning simple, engaging, and project‑oriented with real examples and source code.