首页 > 解决方案 > 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?

标签: pythonsql

解决方案


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


推荐阅读