python - 使用 tkinter 从 python 中的 MS SQL 服务器数据库插入树视图行
问题描述
我编写了这段代码,它给了我代码下方屏幕截图中显示的错误。表格中每个单元格中的文本都带有引号和逗号。
我搜索了谷歌,我得到的只是关于这个问题,我什至没有看到有人在 YouTube 或这里遇到过。这是我的第一次尝试,所以我基本上不明白问题出在哪里。
我正在尝试制作一个非常简单的 UI,以通过连接到 MS SQL Server 在使用 tkinter 中的树视图创建的表中显示数据库中表的内容(记录)。当我在 for 循环中插入 using.insert('', 'end', values=i)
时,我得到了带有括号符号、引号和逗号符号的记录。
from tkinter import *
import tkinter as tk
from tkinter import ttk
from tkinter import messagebox
import pyodbc
####### Defining functions #######
def update(rows):
for i in rows:
trv.insert('', 'end', values=i)
#### connecting to the the Microsoft SQL server ####
conn = pyodbc.connect('Driver={SQL Server};'
'Server=DESKTOP-7IKK3PQ;'
'Database=HospAnalyDepart;'
'Trusted_Connection=yes;')
#activating the object for database queries
cursor = conn.cursor()
#------------------------------------------------
### creating window ###
root = Tk()
#creating labeled frames
wrapper1 = LabelFrame(root, text="Patients")
wrapper2 = LabelFrame(root, text="Search")
wrapper3 = LabelFrame(root, text="Patient Data")
wrapper1.pack(fill="both", expand="yes", padx=20, pady=20)
wrapper2.pack(fill="both", expand="yes", padx=20, pady=10)
wrapper3.pack(fill="both", expand="yes", padx=20, pady=20)
#---------------------------------------------------------
#creating the table as a tree view
trv = ttk.Treeview(wrapper1, columns=(1,2,3,4), show="headings", height="6")
trv.pack()
#naming headings
trv.heading(1, text="Patient ID")
trv.heading(2, text="Gender")
trv.heading(3, text="Age")
trv.heading(4, text="Mobile")
#tabel content from the db
query = "SELECT PatientId, Gender, Age, Mobile FROM Patients"
cursor.execute(query)
rows = cursor.fetchall()
update(rows)
#--------------------------------------------------------------------------------
root.title("My Application")
root.geometry("1050x700")
root.mainloop()
解决方案
只需替换以下内容:
def update(rows):
for i in rows:
trv.insert('', 'end', values=(i['Patient ID'], i['Gender'], i['Age'], i['Mobile']))
MS-SQL 数据库将游标值作为字典类型数据返回,为此您需要指定转换。
推荐阅读
- cockroachdb - 关闭 cockroachdb 单节点集群中的时间序列数据
- javascript - 为什么在循环一个空数组后在 angular12 中出现“无法编译错误”?
- powerbi - PowerBI:地图可视化未识别巴西“帕拉”州
- razor - 发布后是否可以在 MVC5 网站页脚中显示版本号?
- symfony - 带有 GetSetMethodNormalizer 的 Symfony 序列化程序返回一个空数组而不是日期
- flutter - Flutter Dio 在一个按钮中发出两个请求,然后错误“异步暂停”
- java - 在 Android Studio 中不打开浏览器运行 URL
- nginx - 查看 NGinx 配置以进行 TLS 处理
- r - 如何在 R 中的 spplot 上添加阴影多边形?
- react-native - 预期的根减速器功能。而是收到:反应本机应用程序中的未定义错误