这两天在折腾Sqlite3 数据库,对于一些小应用,这个Sqlite3 很好用,不需要驱动,又能满足基础需求。抽空写了通用的数据表管理界面,简单实现 查询,修改、新增、删除记录。
用WxPython 实现。
wxPython 4.0.6
Python 3.7.3
一次写完, 要管理什么数据, 改下接口即可,不用逐个写窗口代码。
代码打包下载地址:
https://download.csdn.net/download/seakingx/12012151
# encoding: utf-8
"""
@author: 陈年椰子
@contact: [email protected]
@version: 1.0
@file: main.py
@time: 2019/6/19 0012 11:36
说明
调用数据库编辑界面示范
"""
from SqliteLib import WorkDb
import wx
from DataMF import DMFrame
# 建立2个数据库表 第一次运行建立即可 , 自行用其他工具建立可以
# wb = WorkDb('test.db')
# wb.create_goods()
# wb.create_person()
def goods():
# 展示的字段信息
fld = 'pd_name,sepc_key,g_prc,g_stock'
# 展示的字段标题
fld_head = '商品名称|单位|价格|库存'
# 表名
table_name = 'goods'
# order 是排序字段 , 如不需要排序,则为空
wb_tbl = {'name':table_name,'fld':fld , 'key': '', 'order': 'order by pd_name'}
wb_tbl['fld_head'] = fld_head
# 新建时的缺省数据
wb_tbl['value'] = ('新产品', '', 0, 0)
# 查询关键字的字段
wb_tbl['srch_fld'] = 'pd_name'
# 窗口标题
wb_tbl['Title'] = '商品信息维护'
return wb_tbl
def person():
fld = 'pr_name,phoneno'
fld_head = '姓名|电话'
table_name = 'person'
wb_tbl = {'name':table_name,'fld':fld , 'key': '', 'order': ''}
wb_tbl['fld_head'] = fld_head
wb_tbl['value'] = ('联系人姓名', '123')
wb_tbl['srch_fld'] = 'pr_name'
wb_tbl['Title'] = '联系人信息维护'
return wb_tbl
app = wx.App()
# 商品管理
df = DMFrame(goods())
# 联系人管理
# df = DMFrame(person())
df.Show()
app.MainLoop()
# encoding: utf-8
"""
@author: 陈年椰子
@contact: [email protected]
@version: 1.0
@file: DataMF.py
@time: 2019/6/20 0020 14:39
说明
用于编辑数据库。可以查询、新增、修改
"""
from SqliteLib import WorkDb
import wx
import wx.grid
class DataTable(wx.grid.GridTableBase):
def __init__(self, Table_Dict):
wx.grid.GridTableBase.__init__(self)
work_db_file = "test.db"
self.wb = WorkDb(work_db_file)
fld_str = Table_Dict['fld']
# 这里要重写GridTableBase 的方法 。 具体和网上的类似
# 但我发现 DeleteRow有错误, 只能重写整了一个。
# 代码省略了, 准备打包下载。
class DMFrame(wx.Frame):
def __init__(self, Data_Tbl_Dict):
self.tbl_dict = Data_Tbl_Dict
wx.Frame.__init__(self, None, title=self.tbl_dict['Title'], size=(640, 480))
self.Sizer = wx.BoxSizer(wx.VERTICAL)
self.btn_new = wx.Button(self, -1, "新增")
self.btn_del = wx.Button(self, -1, "删除")
self.key_str = wx.TextCtrl(self, -1)
self.btn_srch = wx.Button(self, -1, "查询")
self.hbox = wx.BoxSizer(wx.HORIZONTAL)
self.hbox.Add(self.btn_new, 0, flag=wx.LEFT, border=10)
self.hbox.Add(self.btn_del, 0, flag=wx.LEFT, border=10)
self.hbox.Add(self.key_str, 0, flag=wx.LEFT, border=10)
self.hbox.Add(self.btn_srch, 0, flag=wx.LEFT, border=10)
self.btn_srch.Bind(wx.EVT_BUTTON, self.SrchData, self.btn_srch)
self.btn_del.Bind(wx.EVT_BUTTON, self.OnDel, self.btn_del)
self.btn_new.Bind(wx.EVT_BUTTON, self.OnNew, self.btn_new)
self.grid = wx.grid.Grid(self)
self.table = DataTable(self.tbl_dict)
self.grid.SetTable(self.table, True)
self.Sizer.Add(self.hbox, 0, wx.TOP, border=5)
self.Sizer.Add(self.grid, 1, wx.TOP|wx.EXPAND, border=5)
self.CreateStatusBar()
self.SetStatusText("编辑信息!")
def OnNew(self, event):
self.table.AppendRows()
self.grid.Refresh()
def OnDel(self, event):
cur_row = self.grid.GetGridCursorRow()
row = self.table.data[cur_row]
pd_name = self.table.GetValue(cur_row,1)
dlg = wx.MessageDialog(None, u"确定删除[{}]吗?".format(pd_name), u"警告", wx.YES_NO | wx.ICON_QUESTION)
if dlg.ShowModal() == wx.ID_YES:
pd_id = self.table.GetValue(cur_row, 0)
self.table.Deletedata(pd_id)
dlg.Destroy()
self.grid.ClearGrid()
self.table = DataTable(self.tbl_dict)
self.grid.SetTable(self.table, True)
self.grid.ForceRefresh()
def SrchData(self,event):
key_in = self.key_str.GetValue()
self.grid.ClearGrid()
if len(key_in) > 0:
self.tbl_dict['key'] = "where {0} like '%{1}%' ".format(self.tbl_dict['srch_fld'], key_in)
self.table = DataTable(self.tbl_dict)
self.SetStatusText("查询包含【{}】信息!".format(key_in))
else:
self.tbl_dict['key'] = ''
self.table = DataTable(self.tbl_dict)
self.SetStatusText("查询所有信息!".format(key_in))
self.grid.SetTable(self.table, True)
self.grid.ForceRefresh()
SqliteLib.py
# encoding: utf-8
"""
@author: 陈年椰子
@contact: [email protected]
@version: 1.0
@file: SqliteLib.py
@time: 2019/6/20 0020 15:19
说明 sqlite3 数据访问接口
"""
import sqlite3
# 本地数据库
class WorkDb:
def __init__(self, work_db):
self.db = work_db
def connect(self):
return sqlite3.connect(self.db)
def run_sql(self, sql):
conn = self.connect()
cursor = conn.cursor()
ret = cursor.execute(sql)
cursor.close()
conn.commit()
conn.close()
return ret
def insert_sql(self, sql, data):
conn = self.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.commit()
conn.close()
def update_sql(self, sql, data):
conn = self.connect()
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.commit()
conn.close()
def get_sql(self, sql):
conn = self.connect()
cursor = conn.cursor()
cursor.execute(sql)
values = cursor.fetchall()
cursor.close()
conn.close()
return values
def create_goods(self):
# 建立数据库表示范1
# 商品名称||单位||价格||库存
# pd_name||sepc_key||g_prc||g_stock
# 执行一条语句,创建 goods
sql = '''create table goods (id integer primary key autoincrement
, pd_name varchar(30)
, sepc_key varchar(30)
, g_prc INTEGER
, g_stock INTEGER
)'''
self.run_sql(sql)
def create_person(self):
# 建立数据库表示范2
# 姓名||联系电话
# pr_name||phoneno
sql = '''create table person(id integer primary key autoincrement
, pr_name varchar(30)
, phoneno varchar(30)
)'''
self.run_sql(sql)
def data_list(self,table_dict):
table_name = table_dict['name']
table_fld = table_dict['fld']
table_key = table_dict['key']
table_order = table_dict['order']
sql = "select id,{0} from {1} {2} {3}".format(table_fld, table_name, table_key, table_order)
data = self.get_sql(sql)
return data
def data_new(self,table_dict):
table_name = table_dict['name']
table_fld = table_dict['fld']
data_value = table_dict['value']
sql = "insert into {0}({1}) values {2} ".format(table_name, table_fld, data_value)
# print(sql)
self.run_sql(sql)
sql = 'select max(id) from {}'.format(table_name)
ret = self.get_sql(sql)
if len(ret) == 0:
return 0
else:
return ret[0][0]
def data_del(self, table_dict, id):
table_name = table_dict['name']
sql = "delete from {0} where id={1}".format(table_name, id)
self.run_sql(sql)
def data_update(self, table_dict, id):
tbl = table_dict['name']
fld = table_dict['upd_fld']
value = table_dict['upd_value']
sql = '''
update {} set {}='{}'
where id = {}
'''.format(tbl, fld, value, id)
# print(sql)
self.run_sql(sql)
代码打包下载地址: