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 数据库和表。这不仅提高了用户体验,还简化了数据库管理的流程。如果你有任何问题或建议,欢迎在评论区留言。

相关推荐
深蓝海拓3 分钟前
使用@property将类方法包装为属性
开发语言·python
福运常在1 小时前
股票数据API(19)次新股池数据
java·python·maven
多看书少吃饭1 小时前
Vue3 + Java + Python 打造企业级大模型知识库(含 SSE 流式对话完整源码)
java·python·状态模式
Z.风止1 小时前
Large Model-learning(2)
开发语言·笔记·python·leetcode
蓝天守卫者联盟11 小时前
玩具喷涂废气治理厂家:行业现状、技术路径与选型指南
大数据·运维·人工智能·python
m0_738120721 小时前
我的创作纪念日0328
java·网络·windows·python·web安全·php
red1giant_star1 小时前
浅析文件类漏洞原理与分类——含payload合集与检测与防护思路
python·安全
tryCbest2 小时前
Python之Flask开发框架(第一篇) — 从安装到第一个应用
开发语言·python·flask
zhangzeyuaaa2 小时前
Python getter/setter 正确用法详解
开发语言·python
源码之家2 小时前
计算机毕业设计:Python智慧交通大数据分析平台 Flask框架 requests爬虫 出行速度预测 拥堵预测(建议收藏)✅
大数据·hadoop·爬虫·python·数据分析·flask·课程设计