Python写入SQLite数据库报错:'tuple'对象无'Personal_id'属性
问题描述
编写了一段将数据存入SQLite数据库的Python代码,但运行时出现错误:AttributeError: 'tuple' object has no attribute 'Personal_id'
代码示例
import sqlite3 conn = sqlite3.connect('db.db') c = conn.cursor() def log_in(patient): with conn: c.execute("""INSERT INTO patient_office_syndrome VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", (patient.Personal_id,patient.first_name, patient.last_name, patient.age, patient.phone, patient.gender, patient.weight, patient.height)) patient_1 = ('1409903748846541','siri','pat','25','06119433332',0,'80','190') log_in(patient_1) conn.commit() conn.close()
报错回溯
Traceback (most recent call last): File
"c:\Users\User\Desktop\db_and_admin_web\main.py", line 19, inlog_in(patient_1) File
"c:\Users\User\Desktop\db_and_admin_web\main.py", line 11, in
log_in (?, ?, ?, ?, ?, ?, ?, ?)""",
(patient.Personal_id,patient.first_name, patient.last_name,
patient.age, patient.phone, patient.gender, patient.weight,
patient.height)) AttributeError: 'tuple' object has no attribute
'Personal_id'
问题原因及解决方法
原因
你定义的patient_1是一个元组(tuple),元组只能通过索引访问元素(比如patient_1[0]),但log_in函数里却试图用属性访问的方式(比如patient.Personal_id)获取值,这就导致了报错。
解决方法
有两种常见修复方式:
方式一:直接传递元组到execute方法
既然patient_1已经是和插入字段顺序匹配的元组,直接把它作为execute的第二个参数即可:
def log_in(patient): with conn: c.execute("""INSERT INTO patient_office_syndrome VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", patient)
方式二:用类定义Patient对象
如果想保留属性访问的写法,先定义一个Patient类,创建类实例再传入:
import sqlite3 conn = sqlite3.connect('db.db') c = conn.cursor() class Patient: def __init__(self, Personal_id, first_name, last_name, age, phone, gender, weight, height): self.Personal_id = Personal_id self.first_name = first_name self.last_name = last_name self.age = age self.phone = phone self.gender = gender self.weight = weight self.height = height def log_in(patient): with conn: c.execute("""INSERT INTO patient_office_syndrome VALUES (?, ?, ?, ?, ?, ?, ?, ?)""", (patient.Personal_id,patient.first_name, patient.last_name, patient.age, patient.phone, patient.gender, patient.weight, patient.height)) # 创建Patient实例 patient_1 = Patient('1409903748846541','siri','pat','25','06119433332',0,'80','190') log_in(patient_1) conn.commit() conn.close()
额外提示
- 使用
with conn上下文管理器时,会自动提交事务,后面的conn.commit()可以省略,避免重复提交。 - 建议在SQL语句中明确指定插入的字段名,比如
INSERT INTO patient_office_syndrome (personal_id, first_name, ...) VALUES (?, ?, ...),这样即使字段顺序变化也不会出错。
内容的提问来源于stack exchange,提问作者siripat

