Qsqlite代码实现增删改查
时间: 2023-03-16 08:43:45 浏览: 192
SQLite 的增删改查代码实现的原理是:使用SQL语句来实现对数据库的增删改查操作,如增加一条记录:INSERT INTO table_name (column1, column2,...) VALUES (value1, value2,....); 删除一条记录:DELETE FROM table_name WHERE some_column = some_value; 修改一条记录:UPDATE table_name SET column1 = value1, column2 = value2,... WHERE some_column = some_value; 查询一条记录:SELECT column1, column2,... FROM table_name WHERE some_column = some_value;
相关问题
在pyqt中做可以增删改查的商品数据库的方式有什么?步骤是什么?给出一个有增删改查功能的商品数据库界面的完整代码
在PyQt中实现可以增删改查的商品数据库的一种方式是使用Qt的数据库模块(QtSql)结合SQLite数据库完成。步骤如下:
1. 安装PyQt和SQLite数据库
在Python环境中使用pip安装PyQt和sqlite3模块:
```
pip install PyQt5
```
2. 创建SQLite数据库
使用SQLiteStudio或其他SQLite管理工具创建一个名为“goods.db”的数据库,其中包含一个名为“goods”的数据表,数据表包含以下字段:
```
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
price REAL NOT NULL,
quantity INTEGER NOT NULL
```
3. 设计GUI界面
使用Qt Designer设计一个GUI界面,包含以下控件:
- QLabel:显示标题和各个字段的标签
- QLineEdit:输入框,用于输入商品名称、价格、数量等信息
- QPushButton:按钮,用于执行增删改查操作
- QTableWidget:表格控件,用于显示数据库中的商品信息
4. 编写程序逻辑
在Python代码中实现以下操作:
- 连接SQLite数据库
- 实现增加、删除、修改、查询操作
- 将数据库中的数据显示在表格中
完整的代码如下:
```python
import sys
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
from PyQt5.QtWidgets import QApplication, QMainWindow, QTableWidgetItem
from PyQt5.QtGui import QIcon
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('商品数据库')
self.setWindowIcon(QIcon('icon.png'))
self.setGeometry(100, 100, 800, 600)
self.initUI()
def initUI(self):
self.labels = ['ID', '名称', '价格', '数量']
self.table = QTableWidget(self)
self.table.setRowCount(0)
self.table.setColumnCount(len(self.labels))
self.table.setHorizontalHeaderLabels(self.labels)
self.table.setGeometry(50, 50, 700, 400)
self.name_label = QLabel('名称', self)
self.name_label.setGeometry(50, 480, 50, 30)
self.name_edit = QLineEdit(self)
self.name_edit.setGeometry(120, 480, 150, 30)
self.price_label = QLabel('价格', self)
self.price_label.setGeometry(300, 480, 50, 30)
self.price_edit = QLineEdit(self)
self.price_edit.setGeometry(370, 480, 150, 30)
self.quantity_label = QLabel('数量', self)
self.quantity_label.setGeometry(550, 480, 50, 30)
self.quantity_edit = QLineEdit(self)
self.quantity_edit.setGeometry(620, 480, 150, 30)
self.add_button = QPushButton('增加', self)
self.add_button.setGeometry(50, 530, 100, 30)
self.add_button.clicked.connect(self.add_item)
self.delete_button = QPushButton('删除', self)
self.delete_button.setGeometry(200, 530, 100, 30)
self.delete_button.clicked.connect(self.delete_item)
self.update_button = QPushButton('修改', self)
self.update_button.setGeometry(350, 530, 100, 30)
self.update_button.clicked.connect(self.update_item)
self.search_button = QPushButton('查询', self)
self.search_button.setGeometry(500, 530, 100, 30)
self.search_button.clicked.connect(self.search_item)
self.show_table()
def show_table(self):
self.db = QSqlDatabase.addDatabase('QSQLITE')
self.db.setDatabaseName('goods.db')
self.db.open()
query = QSqlQuery()
query.exec_("SELECT * FROM goods")
row = 0
self.table.setRowCount(0)
while query.next():
self.table.insertRow(row)
for col in range(len(self.labels)):
item = QTableWidgetItem(str(query.value(col)))
self.table.setItem(row, col, item)
row += 1
def add_item(self):
name = self.name_edit.text()
price = self.price_edit.text()
quantity = self.quantity_edit.text()
query = QSqlQuery()
query.exec_("INSERT INTO goods (name, price, quantity) VALUES ('{}', '{}', '{}')".format(name, price, quantity))
self.show_table()
def delete_item(self):
selected = self.table.selectedIndexes()
if selected:
id = self.table.item(selected[0].row(), 0).text()
query = QSqlQuery()
query.exec_("DELETE FROM goods WHERE id={}".format(id))
self.show_table()
def update_item(self):
selected = self.table.selectedIndexes()
if selected:
id = self.table.item(selected[0].row(), 0).text()
name = self.name_edit.text()
price = self.price_edit.text()
quantity = self.quantity_edit.text()
query = QSqlQuery()
query.exec_("UPDATE goods SET name='{}', price='{}', quantity='{}' WHERE id={}".format(name, price, quantity, id))
self.show_table()
def search_item(self):
name = self.name_edit.text()
query = QSqlQuery()
query.exec_("SELECT * FROM goods WHERE name LIKE '%{}%'".format(name))
row = 0
self.table.setRowCount(0)
while query.next():
self.table.insertRow(row)
for col in range(len(self.labels)):
item = QTableWidgetItem(str(query.value(col)))
self.table.setItem(row, col, item)
row += 1
if __name__ == '__main__':
app = QApplication(sys.argv)
window = MainWindow()
window.show()
sys.exit(app.exec_())
```
在程序中先定义了一个MainWindow类,继承自QMainWindow。在MainWindow类中,定义了GUI界面的各个控件,并且实现了增加、删除、修改、查询操作。在show_table()方法中,连接SQLite数据库,并且执行SELECT语句获取数据库中的数据,然后将数据显示在表格中。在add_item()、delete_item()、update_item()、search_item()方法中,通过QSqlQuery对象执行INSERT、DELETE、UPDATE、SELECT语句,实现增删改查操作。最后,在主程序中创建一个QApplication对象,并且创建一个MainWindow对象,调用show()方法显示GUI界面,调用app.exec_()方法进入消息循环。
使用python代码的pyqt库做一个软件,实现首先有一个登录界面,登录后做一个界面实现数据库管理系统,实现内容导入,数据库增删改查
好的,以下是一个简单的实现代码,具体的实现过程中需要根据实际需求进行调整和优化:
```python
from PyQt5.QtWidgets import QApplication, QMainWindow, QWidget, QLabel, QLineEdit, QPushButton, QTableWidget, QTableWidgetItem, QComboBox, QFileDialog, QMessageBox
from PyQt5.QtSql import QSqlDatabase, QSqlQuery
import sys
class LoginWindow(QWidget):
def __init__(self):
super().__init__()
self.setWindowTitle('登录')
self.resize(300, 200)
self.username_label = QLabel('用户名:', self)
self.username_label.move(50, 50)
self.username_edit = QLineEdit(self)
self.username_edit.move(100, 50)
self.password_label = QLabel('密码:', self)
self.password_label.move(50, 100)
self.password_edit = QLineEdit(self)
self.password_edit.setEchoMode(QLineEdit.Password)
self.password_edit.move(100, 100)
self.login_button = QPushButton('登录', self)
self.login_button.move(100, 150)
self.login_button.clicked.connect(self.login)
def login(self):
username = self.username_edit.text()
password = self.password_edit.text()
# 进行用户名和密码验证
if username == 'admin' and password == '123456':
self.hide()
self.main_window = MainWindow()
self.main_window.show()
else:
QMessageBox.warning(self, '错误', '用户名或密码错误!')
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.setWindowTitle('数据库管理系统')
self.resize(800, 600)
self.central_widget = QWidget(self)
self.setCentralWidget(self.central_widget)
self.database_label = QLabel('选择数据库:', self.central_widget)
self.database_label.move(50, 50)
self.database_combo = QComboBox(self.central_widget)
self.database_combo.move(150, 50)
self.database_combo.addItems(['db1', 'db2', 'db3'])
self.database_combo.currentIndexChanged.connect(self.select_database)
self.table_label = QLabel('选择表格:', self.central_widget)
self.table_label.move(50, 100)
self.table_combo = QComboBox(self.central_widget)
self.table_combo.move(150, 100)
self.table_combo.currentIndexChanged.connect(self.select_table)
self.table_widget = QTableWidget(self.central_widget)
self.table_widget.move(50, 150)
self.table_widget.setColumnCount(3)
self.table_widget.setHorizontalHeaderLabels(['ID', '姓名', '年龄'])
self.import_button = QPushButton('导入数据', self.central_widget)
self.import_button.move(50, 400)
self.import_button.clicked.connect(self.import_data)
self.add_button = QPushButton('添加数据', self.central_widget)
self.add_button.move(200, 400)
self.add_button.clicked.connect(self.add_data)
self.modify_button = QPushButton('修改数据', self.central_widget)
self.modify_button.move(350, 400)
self.modify_button.clicked.connect(self.modify_data)
self.delete_button = QPushButton('删除数据', self.central_widget)
self.delete_button.move(500, 400)
self.delete_button.clicked.connect(self.delete_data)
self.init_database()
def init_database(self):
# 初始化数据库连接
self.db = QSqlDatabase.addDatabase('QSQLITE')
self.db.setDatabaseName('test.db')
if not self.db.open():
QMessageBox.warning(self, '错误', '无法打开数据库!')
return
# 加载数据库表格
query = QSqlQuery()
query.exec_('CREATE TABLE IF NOT EXISTS test(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)')
query.exec_('INSERT INTO test(id, name, age) VALUES(1, "张三", 20)')
query.exec_('INSERT INTO test(id, name, age) VALUES(2, "李四", 25)')
query.exec_('INSERT INTO test(id, name, age) VALUES(3, "王五", 30)')
self.select_database(0)
def select_database(self, index):
# 选择数据库
database_name = self.database_combo.currentText()
self.db.setDatabaseName(database_name + '.db')
# 重新加载数据库表格
self.select_table(0)
def select_table(self, index):
# 选择表格
table_name = self.table_combo.currentText()
query = QSqlQuery()
query.exec_('SELECT * FROM {}'.format(table_name))
self.table_widget.setRowCount(0)
while query.next():
row = self.table_widget.rowCount()
self.table_widget.insertRow(row)
for i in range(3):
item = QTableWidgetItem(str(query.value(i)))
self.table_widget.setItem(row, i, item)
def import_data(self):
# 导入数据
file_name, _ = QFileDialog.getOpenFileName(self, '选择文件', '', 'CSV Files (*.csv)')
if file_name:
with open(file_name, 'r') as f:
data = f.readlines()
query = QSqlQuery()
for line in data:
line = line.strip().split(',')
query.exec_('INSERT INTO test(name, age) VALUES("{}", {})'.format(line[0], line[1]))
self.select_table(0)
def add_data(self):
# 添加数据
query = QSqlQuery()
query.exec_('INSERT INTO test(name, age) VALUES("新用户", 0)')
self.select_table(0)
def modify_data(self):
# 修改数据
rows = self.table_widget.selectedItems()
if len(rows) == 0:
QMessageBox.warning(self, '错误', '请选择要修改的数据!')
return
row = rows[0].row()
id = self.table_widget.item(row, 0).text()
name = self.table_widget.item(row, 1).text()
age = self.table_widget.item(row, 2).text()
query = QSqlQuery()
query.exec_('UPDATE test SET name="{}", age={} WHERE id={}'.format(name, age, id))
self.select_table(0)
def delete_data(self):
# 删除数据
rows = self.table_widget.selectedItems()
if len(rows) == 0:
QMessageBox.warning(self, '错误', '请选择要删除的数据!')
return
row = rows[0].row()
id = self.table_widget.item(row, 0).text()
query = QSqlQuery()
query.exec_('DELETE FROM test WHERE id={}'.format(id))
self.select_table(0)
if __name__ == '__main__':
app = QApplication(sys.argv)
login_window = LoginWindow()
login_window.show()
sys.exit(app.exec_())
```
运行以上代码,即可实现一个简单的登录界面和数据库管理系统。需要注意的是,该代码中使用了SQLite作为数据库,需要安装PyQt5和PyQt5-sqlite模块,并且需要将该代码保存为.py文件并运行。同时,还需要考虑数据的安全性、用户体验等问题。
阅读全文