You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python连接SQL Server插入数据为空,变量显示PY_VARx问题

问题:Python通过pyodbc插入SQL Server时出现PY_VAR占位符且插入空白行

已成功通过pyodbc建立Python与SQL Server的连接,调用自定义create函数向PatientInfo表插入患者信息时,打印变量确认提交内容,终端输出各变量为PY_VAR0至PY_VAR10,数据库中新增空白行。

相关代码

def create(conn):
    try:
        print(f"Full Name: {FullName}")
        print(f"Reference No: {ReferenceNumber}")
        print(f"Phone: {Phone}")
        print(f"Age: {Age}")
        print(f"Address {Address}")
        print(f"Treatment Type: {TreatmentType}")
        print(f"Check In Date: {CheckInDate}")
        print(f"Appointment Date: {AppointmentDate}")
        print(f"Payment Method: {PaymentMethod}")
        print(f" Total Paid: {TotalPaid}")
        print(f"Gender: {Gender}")
        # Print other input values...

        cursor = conn.cursor()
        cursor.execute(
            'INSERT INTO PatientInfo(FullName, ReferenceNumber, Phone, Age, Address, TreatmentType, CheckInDate, AppointmentDate, PaymentMethod, TotalPaid, Gender) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
            (
                FullName.get(),
                ReferenceNumber.get(),
                Phone.get(),
                Age.get(),
                Address.get(),
                TreatmentType.get(),
                CheckInDate.get(),
                AppointmentDate.get(),
                PaymentMethod.get(),
                TotalPaid.get(),
                Gender.get(),
                # Add similar lines for other input values...
            )
        )
        conn.commit()
        print("Data successfully inserted.")
    except pyodbc.Error as e:
        # Handle database errors here
        print(f"Database error: {e}")
    except Exception as e:
        # Handle other exceptions here
        print(f"Error: {e}")

# Usage example:
conn = pyodbc.connect(
    'Driver={ODBC Driver 17 for SQL Server};'
    'Server=DESKTOP-6CDVKVT\SQLEXPRESS;'
    'Database=Dhoolacade;'
    'Trusted_Connection=yes;'
)

# Call the create() function with the established connection
create(conn)

# Close the connection when done
conn.close()

终端输出

C:\Users\User\Desktop\Dashboard\venv\Scripts\python.exe C:\Users\User\Desktop\LoginForm\login.py 
Full Name: PY_VAR0
Reference No: PY_VAR1
Phone: PY_VAR2
Age: PY_VAR3
Address PY_VAR4
Treatment Type: PY_VAR5
Check In Date: PY_VAR6
Appointment Date: PY_VAR7
Payment Method: PY_VAR8
Total Paid: PY_VAR9
Gender: PY_VAR10
Data successfully inserted.

原因分析

  1. PY_VARx是Tkinter控件对象的默认字符串表示:打印的是控件对象本身,而非控件存储的实际值,说明打印时未调用.get()方法获取内容。
  2. 控件值为空或未正确传递:虽然execute语句中用了.get(),但如果控件未正确绑定用户输入、作用域内未正确引用控件,或用户未输入内容,.get()会返回空字符串,导致数据库插入空白行。

解决方案

1. 打印控件实际值而非对象

修改打印语句,调用.get()获取控件内容,确认要插入的数据:

print(f"Full Name: {FullName.get()}")
print(f"Reference No: {ReferenceNumber.get()}")
# 其余字段同理修改

2. 确保控件作用域正确

如果FullName、ReferenceNumber等是Tkinter控件实例,需确保它们在create函数的作用域内可用。建议将控件作为参数传递给函数,避免依赖全局变量:

# 修改函数定义,接收控件参数
def create(conn, full_name, reference_num, phone, age, address, treatment_type, checkin_date, appointment_date, payment_method, total_paid, gender):
    try:
        # 先获取并打印实际值
        fn = full_name.get()
        rn = reference_num.get()
        print(f"Full Name: {fn}")
        print(f"Reference No: {rn}")
        # 其余字段同理

        # 插入前验证必填字段
        if not fn or not rn:
            print("Full Name和Reference Number不能为空")
            return

        cursor = conn.cursor()
        cursor.execute(
            'INSERT INTO PatientInfo(FullName, ReferenceNumber, Phone, Age, Address, TreatmentType, CheckInDate, AppointmentDate, PaymentMethod, TotalPaid, Gender) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);',
            (fn, rn, phone.get(), age.get(), address.get(), treatment_type.get(), checkin_date.get(), appointment_date.get(), payment_method.get(), total_paid.get(), gender.get())
        )
        conn.commit()
        print("Data successfully inserted.")
    # 异常处理部分保留
    except pyodbc.Error as e:
        print(f"Database error: {e}")
    except Exception as e:
        print(f"Error: {e}")

# 调用时传入控件对象
create(conn, FullName, ReferenceNumber, Phone, Age, Address, TreatmentType, CheckInDate, AppointmentDate, PaymentMethod, TotalPaid, Gender)

3. 验证控件绑定状态

如果使用StringVar等变量绑定控件,确保已正确关联:

# 示例:正确绑定StringVar和Entry控件
full_name_var = StringVar()
full_name_entry = Entry(root, textvariable=full_name_var)
# 获取值时用full_name_var.get()

内容的提问来源于stack exchange,提问作者Abdilahi Yusuf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.11 15:07:27