首页 > 解决方案 > 使用 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()

截屏

标签: pythonsql-serverfor-loopinserttreeview

解决方案


只需替换以下内容:

def update(rows):
    for i in rows:
        trv.insert('', 'end', values=(i['Patient ID'], i['Gender'], i['Age'], i['Mobile']))

MS-SQL 数据库将游标值作为字典类型数据返回,为此您需要指定转换。


推荐阅读