我正在用PyQt5构建一个桌面应用程序,用于连接MySQL数据库、从中加载数据、将数据插入MySQL数据库和更新MySQL数据库。我所想到的更新数据库和将数据插入数据库的方法是有效的。但我觉得在计算速度方面应该有一种更快的方法。如果有人能帮忙,那将是非常有帮助的。我现在更新数据库的是这个-
def log_change(self, item):
self.changed_items.append([item.row(),item.column()])
# I connect this function to the item changed signal to log any cells which have been changed
def update_db(self):
# Creating an empty list to remove the duplicated cells from the initial list
self.changed_items_load= []
[self.changed_items_load.append(x) for x in self.changed_items if x not in self.changed_items_load]
# loop through the changed_items list and remove cells with no values in them
for db_wa in self.changed_items_load:
if self.tableWidget.item(db_wa[0],db_wa[1]).text() == "":
self.changed_items_load.remove(db_wa)
try:
mycursor = mydb.cursor()
# loop through the list and update the database cell by cell
for ecr in self.changed_items_load:
command = ("update table1 set `{col_name}` = %s where id=%s;")
# table widget column name matches db table column name
data = (str(self.tableWidget.item(ecr[0],ecr[1]).text()),int(self.tableWidget.item(ecr[0],0).text()))
mycursor.execute(command.format(col_name = self.col_names[ecr[1]]),data)
# self.col_names is a list of the tableWidget columns
mydb.commit()
mycursor.close()
except OperationalError:
Msgbox = QMessageBox()
Msgbox.setText("Error! Connection to database lost!")
Msgbox.exec()
except NameError:
Msgbox = QMessageBox()
Msgbox.setText("Error! Connect to database!")
Msgbox.exec()
为了将数据和新行插入数据库,我可以在网上找到一些相关信息。但我无法同时插入多行,也无法为每行插入不同的列长度。比如,如果我想在第1行只插入2列,然后在第2行插入3列…诸如此类。
def insert_db(self):
# creating a list of each column
self.a = [self.tableWidget.item(row,1).text() for row in range (self.tableWidget.rowCount()) if self.tableWidget.item(row,1) != None]
self.b = [self.tableWidget.item(row,2).text() for row in range (self.tableWidget.rowCount()) if self.tableWidget.item(row,2) != None]
self.c = [self.tableWidget.item(row,3).text() for row in range (self.tableWidget.rowCount()) if self.tableWidget.item(row,3) != None]
self.d = [self.tableWidget.item(row,4).text() for row in range (self.tableWidget.rowCount()) if self.tableWidget.item(row,4) != None]
try:
mycursor = mydb.cursor()
mycursor.execute("INSERT INTO table1(Name, Date, Quantity, Comments) VALUES ('%s', '%s', '%s', '%s')" %(''.join(self.a),
''.join(self.b),
''.join(self.c),
''.join(self.d)))
mydb.commit()
mycursor.close()
except OperationalError:
Msgbox = QMessageBox()
Msgbox.setText("Error! Connection to database lost!")
Msgbox.exec()
except NameError:
Msgbox = QMessageBox()
Msgbox.setText("Error! Connect to database!")
Msgbox.exec()
我们将不胜感激。谢谢
如果我想在第1行只插入2列,然后在第2行插入3列
否。给定的数据库表具有特定数量的列。这是";表";。
INSERT
向表中添加新行。可以构造插入多行的单个SQL语句;一次完成";。
UPDATE
修改一个表的一行或多行。行由Update语句中指定的某些条件指示。
用%s
构造SQL是有风险的——如果插入的字符串中有引号,就会遇到麻烦。
(我希望这些评论能帮助你进入理解数据库的下一阶段。(