Reputation: 1
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?
Upvotes: 2
Views: 133
Reputation: 1648
emp_list[i]
returns a tuple and naturally it doesn't have any of attributes you are looking for.
If you want to get values by attributes, you could look at namedtuple
employee = namedtuple('Employee', ['first', 'last', 'pay'])
emps = [employee('John', 'Wick', '1000000'), ...)
insert_emploees(emps)
But a simpler solution would be just to handle your tuples better:
curs.execute("INSERT INTO employees VALUES (:first, :last, :pay)",
dict(zip(['first', 'last', 'pay'], *i)))
Upvotes: 1
Reputation: 41
You just have a list of tuples. It seems like you meant to have a list of employee objects, to do so change
emps = [("Brenda", "Johnson", "4000"), ("Reza", "Amir", "5000")]
to
emps = [Employee("Brenda", "Johnson", "4000"), Employee("Reza", "Amir", "5000")]
Upvotes: 1
Reputation: 493
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
Upvotes: 1