当前位置:   article > 正文

【PyQt】读取MySQL数据填充到Qt表格控件中

【PyQt】读取MySQL数据填充到Qt表格控件中

说明:代码是从项目源代码中抽取,需要进行适应性修改,不保证可运行。

1 读取MySQL数据库

需要提前安装 pymysql 库。

简单版本:

  1. # 需安装 pymysql 库
  2. import pymysql
  3. import sys
  4. try:
  5. con = pymysql.connect(host='localhost', port='3306',
  6. user='kitty', password='123456',
  7. database='user_db')
  8. except Exception:
  9. pass
  10. # QMessageBox.information(None, '错误', 'MySQL数据库连接错误')
  11. # con 就代表数据库的链接
  12. cur = con.cursor()
  13. sql = "select * from t_user where userid = %s and userpwd = %s"
  14. data = ("Kitty","123")
  15. cur.execute(sql, data)
  16. result = cur.fetchall()
  17. cur.close() # 关闭游标
  18. con.close() # 关闭数据库链接
  19. print(result)

包装成类:

  1. import pymysql
  2. class MyDB:
  3. """ 简单包装 """
  4. def __init__(self):
  5. self.con = None
  6. self.initCon()
  7. def initCon(self):
  8. try:
  9. con = pymysql.connect(host='localhost', port='3306',
  10. user='kitty', password='123456',
  11. database='user_db')
  12. self.con = con
  13. except Exception:
  14. pass
  15. # QMessageBox.information(None, '错误', 'MySQL数据库连接错误')
  16. def query(self, sql, data=None):
  17. """
  18. 查询数据,data只能是单个元组,不能是元组的列表
  19. 使用 %s 占位符,防止SQL注入
  20. :param sql: 带有%s占位符的SQL语句 "SELECT * FROM user WHERE uid=%s and name=%s and pwd=%s "
  21. :param data: (uid,name,pwd...)
  22. :return:
  23. """
  24. if not self.con:
  25. self.initCon()
  26. con = self.con
  27. cur = con.cursor()
  28. cur.execute(sql, data)
  29. l = cur.fetchall()
  30. cur.close()
  31. return l
  32. def execute(self, sql, data):
  33. """
  34. 新增/删除/更新数据,注意:data必须是list!里面可包裹1到多个元组
  35. 此函数不返回数据。支持insert,delete,update
  36. insert: insert into user(name,pwd) values(%s,%s)
  37. delete: update user set delflag=1 where id=%s
  38. update: update user set name=%s and pwd=%s where id = %s
  39. :param sql: 带有%s占位符的SQL语句
  40. :param data: [('tom','123456'),('jerry','123456')]
  41. :return:
  42. """
  43. if not self.con:
  44. self.initCon()
  45. con = self.con
  46. try:
  47. cur = con.cursor()
  48. cur.executemany(sql, data)
  49. con.commit()
  50. # return cur.lastrowid
  51. except Exception:
  52. pass
  53. # con.rollback()
  54. # QMessageBox.information(None, '错误', '操作出现错误')
  55. # traceback.print_exc() # 可打印错误行号,异常的详细内容
  56. finally:
  57. cur.close()
  58. def insertSglRtnId(self, sql, data):
  59. """
  60. 插入单条数据,并返回新插入记录id
  61. :param sql: 带有%s占位符的SQL语句
  62. :param data: 数据元组
  63. :return: lastrowid
  64. """
  65. if not self.con:
  66. self.initCon()
  67. con = self.con
  68. try:
  69. cur = con.cursor()
  70. cur.execute(sql, data)
  71. con.commit()
  72. return cur.lastrowid
  73. except Exception:
  74. pass
  75. # traceback.print_exc() # 可打印错误行号,异常的详细内容
  76. finally:
  77. cur.close()
  78. def cleartbl(self, tablename):
  79. """
  80. 清空表内容
  81. :return:
  82. """
  83. if not self.con:
  84. self.initCon()
  85. con = self.con
  86. cur = con.cursor()
  87. cur.execute("delete from " + tablename + " where 1=1 ")
  88. con.commit()
  89. cur.close()
  90. def close(self):
  91. """
  92. 关闭数据库链接,必须要调用
  93. :return:
  94. """
  95. if self.con:
  96. self.con.close()
  97. if __name__ == "__main__":
  98. pass

使用方法:

  1. sql = "select * from t_user where username = %s usersex = %s"
  2. data = ('Kitty', 'male')
  3. db = MyDB()
  4. if not db:
  5. records = db.query(sql, data)
  6. db.close()
  7. print(records)

2 填充到Qt的表格控件中

  1. def fillTbl(self):
  2. # ...省略读取数据库代码
  3. # records 是从数据库中获取的数据list
  4. # 填充表格控件
  5. header = ['ID', '姓名', '密码', '性别', '年龄', '排序号'] # 设置表头
  6. cols = len(header) # 列数
  7. rows = len(records) # 行数
  8. table = self.tbl # 表格控件
  9. table.setColumnCount(cols)
  10. table.setRowCount(rows)
  11. table.horizontalHeader().setDefaultAlignment(Qt.AlignLeft | Qt.AlignVCenter) # 左右居左 上下居中
  12. table.setHorizontalHeaderLabels(header)
  13. # 遍历records 逐项填充每个单元格
  14. for i in range(0, rows):
  15. for j in range(0, cols):
  16. if not records[i][j]:
  17. item = QTableWidgetItem(str(""))
  18. else:
  19. item = QTableWidgetItem(str(records[i][j]))
  20. item.setToolTip(str(records[i][j])) # 鼠标悬停提示气泡,方便显示过长内容
  21. table.setItem(i, j, item) # 设置i行j列的内容

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/382753
推荐阅读
相关标签
  

闽ICP备14008679号