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()
效果如圖: