python - Inserting multiple values into a database
问题描述
I wrote a method to add a single employee to a database:
def insert_employee(emp):
conn = sqlite3.connect('employees.db')
curs = conn.cursor()
with conn:
curs.execute("INSERT INTO employees VALUES (:first, :last, :pay)",
{'first': emp.first, 'last': emp.last, 'pay': emp.pay})
conn.commit()
conn.close()
This works:
emp1 = Employee("Josh", "Brandon", "2000")
DataBase.insert_employee(emp1)
I, then, expanded it to add a list of employees:
def insert_employees(emp_list):
conn = sqlite3.connect('employees.db')
curs = conn.cursor()
with conn:
for i in range(2):
curs.execute("INSERT INTO employees VALUES (:first, :last, :pay)",
{'first': emp_list[i].first, 'last': emp_list[i].last, 'pay': emp_list[i].pay})
conn.commit()
conn.close()
This does not work:
emps = [("Brenda", "Johnson", "4000"), ("Reza", "Amir", "5000")]
DataBase.insert_employees(emps)
I get an AttributeError
that says 'tuple' object has no attribute 'first'
.
What am I missing or doing werong?
解决方案
This creates an instance of a class, you used it´s getter functions like first, last, etc.
emp1 = Employee("Josh", "Brandon", "2000")
But this is just an array
emps = [("Brenda", "Johnson", "4000"), ("Reza", "Amir", "5000")]
Depending on how you get your data and how much you want to mutate it, you could just access the keys
emp_list[i][0]
instead of first
emp_list[i][1]
instead of last
推荐阅读
- python - ValueError:以 10 为底的 int() 的无效文字:“孟买到迪拜”
- java - 服务器关闭带有套接字的客户端的问题
- reactjs - React Redux,状态中特定项目的更新
- javascript - 无法通过键更改值
- javascript - 使用选择更改选择角度材料表的颜色
- python - 编译 Python 代码时 unindent 不匹配任何外部缩进级别错误
- asp.net - 在 Razor Pages/MVC asp 应用程序中将两个模型链接在一起
- .net - 未从客户端调用的服务器函数
- java - 如何从 XML java 中的标签内部获取图像的链接
- javascript - WCF 服务在本地工作,但在服务器上给出 404