python编程:创建 SQLite 数据库和表的图形用户界面应用程序

在本文中,我将介绍如何使用 wxPython 模块创建一个图形用户界面(GUI)应用程序,该应用程序允许用户选择 SQLite 数据库的存放路径、数据库名称、表名称,并动态添加字段及其类型。以下是具体的实现步骤和代码示例。

C:\pythoncode\new\sqlitegenerator.py

环境准备

首先,确保你已经安装了 wxPythonsqlite3 模块。你可以使用以下命令安装 wxPython

bash 复制代码
pip install wxPython
代码实现

下面是完整的代码实现:

python 复制代码
import wx
import sqlite3
import os

class SQLiteDBCreator(wx.Frame):
    def __init__(self, parent, title):
        super(SQLiteDBCreator, self).__init__(parent, title=title, size=(600, 500))
        
        self.panel = wx.Panel(self)
        
        vbox = wx.BoxSizer(wx.VERTICAL)
        
        # Database Path
        hbox1 = wx.BoxSizer(wx.HORIZONTAL)
        self.db_path_text = wx.TextCtrl(self.panel)
        db_path_btn = wx.Button(self.panel, label='Select Path')
        db_path_btn.Bind(wx.EVT_BUTTON, self.on_select_path)
        hbox1.Add(self.db_path_text, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        hbox1.Add(db_path_btn, flag=wx.ALL, border=5)
        
        # Database Name
        hbox2 = wx.BoxSizer(wx.HORIZONTAL)
        db_name_lbl = wx.StaticText(self.panel, label="Database Name:")
        self.db_name_text = wx.TextCtrl(self.panel)
        hbox2.Add(db_name_lbl, flag=wx.ALL, border=5)
        hbox2.Add(self.db_name_text, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        
        # Table Name
        hbox3 = wx.BoxSizer(wx.HORIZONTAL)
        table_name_lbl = wx.StaticText(self.panel, label="Table Name:")
        self.table_name_text = wx.TextCtrl(self.panel)
        hbox3.Add(table_name_lbl, flag=wx.ALL, border=5)
        hbox3.Add(self.table_name_text, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        
        # Fields List
        self.fields_panel = wx.Panel(self.panel)
        self.fields_sizer = wx.BoxSizer(wx.VERTICAL)
        self.fields_panel.SetSizer(self.fields_sizer)
        
        add_field_btn = wx.Button(self.panel, label="Add Field")
        add_field_btn.Bind(wx.EVT_BUTTON, self.on_add_field)
        
        # Create Button
        create_btn = wx.Button(self.panel, label='Create Database and Table')
        create_btn.Bind(wx.EVT_BUTTON, self.on_create_db)
        
        # Add to vbox
        vbox.Add(hbox1, flag=wx.EXPAND)
        vbox.Add(hbox2, flag=wx.EXPAND)
        vbox.Add(hbox3, flag=wx.EXPAND)
        vbox.Add(self.fields_panel, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        vbox.Add(add_field_btn, flag=wx.ALL|wx.CENTER, border=10)
        vbox.Add(create_btn, flag=wx.ALL|wx.CENTER, border=10)
        
        self.panel.SetSizer(vbox)
        
        self.Centre()
        self.Show()
    
    def on_select_path(self, event):
        with wx.DirDialog(self, "Choose database save directory", "", wx.DD_DEFAULT_STYLE) as dirDialog:
            if dirDialog.ShowModal() == wx.ID_OK:
                self.db_path_text.SetValue(dirDialog.GetPath())
    
    def on_add_field(self, event):
        hbox = wx.BoxSizer(wx.HORIZONTAL)
        
        field_name_text = wx.TextCtrl(self.fields_panel)
        field_type_choice = wx.Choice(self.fields_panel, choices=["INTEGER", "TEXT", "REAL", "BLOB"])
        
        hbox.Add(field_name_text, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        hbox.Add(field_type_choice, proportion=1, flag=wx.EXPAND|wx.ALL, border=5)
        
        self.fields_sizer.Add(hbox, flag=wx.EXPAND)
        self.fields_panel.Layout()
        self.panel.Layout()
    
    def on_create_db(self, event):
        db_path = self.db_path_text.GetValue()
        db_name = self.db_name_text.GetValue()
        table_name = self.table_name_text.GetValue()
        
        if not db_path or not db_name or not table_name:
            wx.MessageBox('Database path, name, and table name are required', 'Error', wx.OK | wx.ICON_ERROR)
            return
        
        fields = []
        for hbox in self.fields_sizer.GetChildren():
            field_name_text = hbox.GetSizer().GetChildren()[0].GetWindow()
            field_type_choice = hbox.GetSizer().GetChildren()[1].GetWindow()
            field_name = field_name_text.GetValue()
            field_type = field_type_choice.GetString(field_type_choice.GetSelection())
            if field_name and field_type:
                fields.append(f"{field_name} {field_type}")
        
        if not fields:
            wx.MessageBox('At least one field is required', 'Error', wx.OK | wx.ICON_ERROR)
            return
        
        db_full_path = os.path.join(db_path, db_name)
        
        try:
            conn = sqlite3.connect(db_full_path)
            cursor = conn.cursor()
            
            create_table_query = f"CREATE TABLE {table_name} ({', '.join(fields)})"
            cursor.execute(create_table_query)
            
            conn.commit()
            conn.close()
            
            wx.MessageBox('Database and table created successfully', 'Success', wx.OK | wx.ICON_INFORMATION)
        except sqlite3.Error as e:
            wx.MessageBox(f"An error occurred: {e}", 'Error', wx.OK | wx.ICON_ERROR)

if __name__ == '__main__':
    app = wx.App(False)
    frame = SQLiteDBCreator(None, "SQLite Database Creator")
    app.MainLoop()

功能简介

  1. 选择数据库存放路径:通过点击"Select Path"按钮,用户可以选择数据库文件的存放目录。
  2. 设置数据库名称:用户可以输入数据库名称。
  3. 设置表名称:用户可以输入表名称。
  4. 添加字段:用户可以动态添加任意数量的字段,每个字段包含字段名称和字段类型(从下拉框中选择)。
  5. 创建数据库和表:点击"Create Database and Table"按钮,根据用户输入的信息创建 SQLite 数据库和表。

使用指南

  1. 运行程序后,首先选择数据库文件的存放路径。
  2. 输入数据库名称和表名称。
  3. 点击"Add Field"按钮添加字段,并为每个字段设置名称和类型。
  4. 添加完所有字段后,点击"Create Database and Table"按钮创建数据库和表。

结果如下:


总结

通过本篇博客介绍的代码示例,你可以轻松创建一个功能完善的 GUI 应用程序,用于动态创建 SQLite 数据库和表。这不仅提高了用户体验,还简化了数据库管理的流程。如果你有任何问题或建议,欢迎在评论区留言。

相关推荐
阿童木写作18 小时前
跨境电商图片翻译工具推荐:批量图片翻译+视频字幕翻译+智能抠图
python·macos·音视频·xcode
cui_ruicheng18 小时前
LangChain 应用开发(十四):Agent 上下文与记忆机制
服务器·人工智能·python·langchain
circuitsosk19 小时前
任务规划器的三种范式对比:ReAct、Plan-and-Execute 与 Tree-of-Thought 在真实业务中的取舍
前端·javascript·python·react.js·llm·ai agent
shehuiyuelaiyuehao19 小时前
算法31,前缀和,可被k整除的子数组
数据结构·python·算法
宸津-代码粉碎机19 小时前
AI攻防战升级!基于Spring AI构建Java应用自动免疫安全体系
java·大数据·开发语言·人工智能·python·安全·spring
测试199819 小时前
如何用appium搭建Android自动化测试框架?
自动化测试·软件测试·python·测试工具·职场和发展·appium·测试用例
程序员大雄学编程20 小时前
微积分46. 无穷级数四大核心性质:从理论到实践的全方位解析
python·学习·微积分·学习工具
数字化转型分享点滴20 小时前
## 工厂数字化管理系统的价值体现:构建制造全流程数据闭环
python
2301_8000742121 小时前
map,list简单方法
windows·python·list
DeepVisionary1 天前
30B 参数打平 1 万亿参数:Meta 开源 Muse Glimmer,跑分 35 对 36
python·自动化