Python:将本地图片批量导入到SQLite数据库中
1 # -*- coding: utf-8 -*- 2 # @Time : 2022/9/2 3 # @Author : leict 4 # @File : PictureToSQLite.py 5 6 import os 7 import sqlite3 8 9 # ============================================== 10 # 图片导入SQLite数据库 11 # ============================================== 12 if __name__ == '__main__': 13 grade = "应用题一年级(上)" 14 # grade = "应用题一年级(下)" 15 # grade = "应用题二年级(上)" 16 # grade = "应用题二年级(下)" 17 # grade = "应用题三年级(上)" 18 # grade = "应用题三年级(下)" 19 # grade = "应用题四年级(上)" 20 # grade = "应用题四年级(下)" 21 # grade = "应用题五年级(上)" 22 # grade = "应用题五年级(下)" 23 # 读取sqlite数据 24 sqlDB = sqlite3.connect("%s.dt" % grade) 25 # 创建游标cursor来执行SQL语句 26 cursor = sqlDB.cursor() 27 # 查询表名 28 cursor.execute("SELECT * FROM picture") 29 # 遍历数据 30 for row in cursor.fetchall(): 31 print("ID: ", row[0]) # 遍历每一列数据 32 33 s1, s2, s3 = 'E:\\IMG', '%s' % grade, '%s_image.png' % str(row[0]) 34 strPath = os.path.join(s1, s2, s3) 35 isExists = os.path.exists(strPath) 36 if isExists: 37 fp = open(strPath, 'rb') 38 img = fp.read() 39 # for循环中批量执行SQL语句 40 sql = """ update picture set image =(?) where _id = '%s' """ % row[0] 41 bb = sqlite3.Binary(img) 42 cursor.execute(sql, (bb,)) 43 sqlDB.commit() 44 print("------------图片修改成功------------") 45 else: 46 print("------------不用替换!!!------------") 47 sqlDB.close()
效果如图: