Итак, я создаю код Python, используя базу данных SQLite, которая хранится в памяти.Я сначала написал этот код со значениями сотрудников уже даны.Затем я внес некоторые изменения в код, в котором пользователь вводит значения, которые будут храниться в базе данных, но кажется, что я делаю что-то не так, потому что, что бы я ни пытался, он все равно возвращает ту же ошибку.
Я пробовал разные вещи.Например, я попытался вместо того, чтобы использовать созданный класс, создавать списки, в которых все хранится.Все та же ошибка.Я не совсем уверен, что я делаю неправильно.
import sqlite3
from Employee import Employee
conn = sqlite3.connect(':memory:')
c = conn.cursor()
c.execute("""CREATE TABLE employees(
first text,
last text,
pay integer
)""")
# here I create a table called 'employees'. It stores the first name, the last name and the payment
def insert_emp(emp): # This is used for inserting employees in the table
with conn:
c.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp.first, 'last': emp.last, 'pay': emp.pay})
def get_emp_by_name(lastname): # Searches for all results with the given LAST name
c.execute("SELECT * FROM employees WHERE last = :last", {'last': lastname})
return c.fetchall()
def update_pay(emp, pay): # Updates payment info
with conn:
c.execute("""UPDATE employees SET pay = :pay WHERE first = :first AND last = :last""",
{'first': emp.first, 'last': emp.last, 'pay': pay})
def del_emp(emp): # Deletes employee
with conn:
c.execute("DELETE from employees WHERE first = :first AND last = :last",
{'first': emp.first, 'last': emp.last})
a = input("First name: ")
b = input("Last name: ")
c = int(input("Payment: ")) # Turn the payment into an integer, because input automatically sets the value as a str
emp_1 = Employee(a, b, c) # Here I try to add the values given by the user in my class that I have created.
insert_emp(emp_1)
emps = get_emp_by_name('Doe')
print(emps)
conn.close()
Это то, что я пытался сделать, используя созданный мной класс.
Вот класс:
class Employee:
def __init__(self, first, last, pay):
self.first = first
self.last = last
self.pay = pay
Я также написал код с уже заданными значениями.
Вот конец кода с заданными значениями (Работает без проблем):
emp_1 = Employee('John', 'Doe', 80000) # Add the employee, using the class that I have created
emp_2 = Employee('Jane', 'Doe', 90000)
insert_emp(emp_1)
insert_emp(emp_2)
emps = get_emp_by_name('Doe')
print(emps)
update_pay(emp_2, 95000)
del_emp(emp_1)
emps = get_emp_by_name('Doe')
print(emps)
conn.close()
Если мы введем, например, Габриэль;Doe;5000;
результат должен быть:
[('Gabriel', 'Doe', 5000)]
Process finished with exit code 0
Но результат, который я на самом деле получаю:
Traceback (most recent call last):
File *location*, line 56, in <module>
insert_emp(emp_1)
File *location*, line 17, in insert_emp
c.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp.first, 'last': emp.last, 'pay': emp.pay})
AttributeError: 'int' object has no attribute 'execute'