PyQt5 (一百零七)使用可视化的方式对SQLite数据库进行增删改查

PyQt5 (一百零七)使用可视化的方式对SQLite数据库进行增删改查_第1张图片

 

PyQt5 操作SQLite数据库 案例
使用可视化的方式对SQLite数据库进行增,删,改,查
QTableView
QSqlTableModel

import sys

from PyQt5.QtCore import Qt
from PyQt5.QtSql import QSqlDatabase, QSqlQuery, QSqlTableModel
from PyQt5.QtWidgets import QApplication, QTableView, QDialog, QVBoxLayout, QPushButton

'''
PyQt5 操作SQLite数据库 案例
使用可视化的方式对SQLite数据库进行增,删,改,查
QTableView
QSqlTableModel

'''

def createDB():
    db = QSqlDatabase.addDatabase('QSQLITE')
    # 指定SQLite数据库的文件名
    db.setDatabaseName('db1.dbx')
    if not db.open():
        print('无法建立与数据库的连接!')
        return False

    query = QSqlQuery()
    query.exec('create table people(id int primary key,name varchar(10),address varchar(50))')
    query.exec('insert into people values(1,"李易峰","济南")')
    query.exec('insert into people values(2,"蜘蛛侠","青岛")')
    db.close()
    return True

def initializeModel(model):
    model.setTable('people')
    model.setEditStrategy(QSqlTableModel.OnFieldChange)
    model.select()
    model.setHeaderData(0,Qt.Horizontal,'ID')
    model.setHeaderData(1,Qt.Horizontal,'姓名')
    model.setHeaderData(2,Qt.Horizontal,'地址')

def createView(title,model):
    view = QTableView()
    view.setModel(model)
    view.setWindowTitle(title)
    return view

def findrow(i):
    delrow = i.row()
    print('del row=%s' % str(delrow),'展示当前数据')


def addrow():
    ret = model.insertRows(model.rowCount(),1)
    print('insertRow=%s' % str(ret),'插入新行')

if __name__ == '__main__':
    app = QApplication(sys.argv)
    db = QSqlDatabase.addDatabase('QSQLITE')
    db.setDatabaseName('db1.dbx')
    model = QSqlTableModel()
    delrow = -1
    initializeModel(model)

    view = createView('展示数据',model)
    view.clicked.connect(findrow)

    dlg = QDialog()
    layout = QVBoxLayout()
    layout.addWidget(view)
    addBtn = QPushButton('添加一行')
    addBtn.clicked.connect(addrow)

    delBtn = QPushButton('删除一行')
    delBtn.clicked.connect(lambda :model.removeRow(view.currentIndex().row()))

    layout.addWidget(view)
    layout.addWidget(addBtn)
    layout.addWidget(delBtn)

    dlg.setLayout(layout)
    dlg.setWindowTitle('数据库 操作实例')
    dlg.resize(500,400)
    dlg.show()
    # createDB()

    sys.exit(app.exec())









你可能感兴趣的:(pyqt5,数据库,sqlite,qt,python,pyqt5)