python编程:SQLite 管理图片数据库

在本博客中,我们将介绍如何使用 wxPython 和 sqlite3 模块构建一个 GUI 应用程序,该程序可以遍历指定文件夹中的所有图片,并将其信息存储到 SQLite 数据库中。
C:\pythoncode\new\InputImageOFFolderTOSqlite.py

项目简介

我们的目标是创建一个程序,该程序能够从用户指定的文件夹中读取图片文件,并将图片的以下信息存储到 SQLite 数据库的 pics 表中:

  • 图片数据(BLOB)
  • 图片文件名
  • 图片完整路径
  • 图片的最后修改日期
  • 图片的 MD5 码
环境设置

在开始编写代码之前,确保你已安装 wxPython 和 SQLite3 模块。可以使用以下命令安装 wxPython:

pip install wxPython
代码实现

以下是实现上述功能的完整 Python 程序:

import wx
import os
import sqlite3
import hashlib
from datetime import datetime

class SQLiteImageImporter(wx.Frame):
    def __init__(self, parent, title):
        super(SQLiteImageImporter, self).__init__(parent, title=title, size=(500, 300))

        self.panel = wx.Panel(self)
        
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        # Directory Selection
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.dir_path_text = wx.TextCtrl(self.panel)
        dir_path_btn = wx.Button(self.panel, label='Select Directory')
        dir_path_btn.Bind(wx.EVT_BUTTON, self.on_select_directory)
        hbox1.Add(self.dir_path_text, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        hbox1.Add(dir_path_btn, flag=wx.ALL, border=5)
        
        # Import Button
        import_btn = wx.Button(self.panel, label='Import Images')
        import_btn.Bind(wx.EVT_BUTTON, self.on_import_images)
        
        vbox.Add(hbox1, flag=wx.EXPAND)
        vbox.Add(import_btn, flag=wx.ALL|wx.CENTER, border=10)
        
        self.panel.SetSizer(vbox)
        
        self.Centre()
        self.Show()
    
    def on_select_directory(self, event):
        with wx.DirDialog(self, "Choose directory with images", "", wx.DD_DEFAULT_STYLE) as dirDialog:
            if dirDialog.ShowModal() == wx.ID_OK:
                self.dir_path_text.SetValue(dirDialog.GetPath())
    
    def on_import_images(self, event):
        dir_path = self.dir_path_text.GetValue()
        
        if not dir_path:
            wx.MessageBox('Directory path is required', 'Error', wx.OK | wx.ICON_ERROR)
            return
        
        db_path = "C:\\pythoncode\\new\\data\\picbase.db"
        
        conn = sqlite3.connect(db_path)
        cursor = conn.cursor()
        
        cursor.execute('''
            CREATE TABLE IF NOT EXISTS pics (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                pic BLOB,
                picname TEXT,
                picpath TEXT,
                picdate TEXT,
                picmd5 TEXT
            )
        ''')
        
        for root, _, files in os.walk(dir_path):
            for filename in files:
                file_path = os.path.join(root, filename)
                if os.path.isfile(file_path) and file_path.lower().endswith(('.png', '.jpg', '.jpeg', '.bmp', '.gif')):
                    with open(file_path, 'rb') as f:
                        pic_data = f.read()
                    
                    picname = filename
                    picpath = file_path
                    picdate = datetime.fromtimestamp(os.path.getmtime(file_path)).strftime('%Y-%m-%d %H:%M:%S')
                    picmd5 = hashlib.md5(pic_data).hexdigest()
                    
                    cursor.execute('''
                        INSERT INTO pics (pic, picname, picpath, picdate, picmd5)
                        VALUES (?, ?, ?, ?, ?)
                    ''', (pic_data, picname, picpath, picdate, picmd5))
        
        conn.commit()
        conn.close()
        
        wx.MessageBox('Images imported successfully', 'Success', wx.OK | wx.ICON_INFORMATION)

if __name__ == '__main__':
    app = wx.App(False)
    frame = SQLiteImageImporter(None, "SQLite Image Importer")
    app.MainLoop()
代码解释
  1. 选择目录:用户可以通过点击“Select Directory”按钮选择包含图片的文件夹。
  2. 导入图片:点击“Import Images”按钮将所选文件夹及其子文件夹中的所有图片文件导入到数据库中。
  3. 数据库结构:数据库表 pics 包含以下字段:
    • pic: 图片数据(BLOB)
    • picname: 图片文件名
    • picpath: 图片完整路径
    • picdate: 图片文件的最后修改日期
    • picmd5: 图片文件的 MD5 码
使用步骤
  1. 运行程序后,首先选择包含图片的文件夹。
  2. 点击“Import Images”按钮,将图片文件导入到数据库中。
  3. 程序会在指定路径 C:\pythoncode\new\data\picbase.db 创建或更新数据库并插入图片信息。
结果如下:

在这里插入图片描述
在这里插入图片描述

结语

通过这个简单的 GUI 应用程序,用户可以方便地将指定文件夹及其子文件夹中的所有图片信息批量导入到 SQLite 数据库中。该程序实现了基本的数据库操作和文件处理功能,是一个不错的学习和实践例子。希望本文能对你有所帮助!如果有任何问题或建议,欢迎留言讨论。

相关推荐

  1. Python数据库编程SQLite、MySQL与MongoDB

    2024-06-07 19:08:02       32 阅读
  2. Python数据库编程全指南SQLite和MySQL实践

    2024-06-07 19:08:02       18 阅读
  3. Python数据库编程实战:sqlite3模块详解

    2024-06-07 19:08:02       19 阅读
  4. Python访问mysql与sqlite3数据库

    2024-06-07 19:08:02       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-06-07 19:08:02       18 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-06-07 19:08:02       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-06-07 19:08:02       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-06-07 19:08:02       20 阅读

热门阅读

  1. golang标准库错误处理及自定义错误处理示例

    2024-06-07 19:08:02       9 阅读
  2. shader 实践的宝藏网站

    2024-06-07 19:08:02       7 阅读
  3. 什么事无线电报,他是怎么实现的

    2024-06-07 19:08:02       7 阅读
  4. 程序员应该有什么职业素养

    2024-06-07 19:08:02       7 阅读
  5. 数据读取长度不正确 python

    2024-06-07 19:08:02       6 阅读
  6. docker镜像转移,mac Linux

    2024-06-07 19:08:02       9 阅读
  7. 多语言for循环遍历总结

    2024-06-07 19:08:02       8 阅读
  8. Qt 富文本 表格列表图片

    2024-06-07 19:08:02       7 阅读