如何使用SQLite修复python 3.x中的" 'int' object has no attribute 'execute' "错误?



所以,我正在使用存储在内存中的SQLite数据库创建一个python代码。我首先使用已经给出的员工值编写了此代码。然后我对用户输入将存储在数据库中的值的代码进行了一些更改,但似乎我做错了什么,因为无论我尝试什么,它仍然返回相同的错误。

我尝试了不同的东西。例如,我尝试不使用我创建的类,而是创建存储所有内容的列表。还是同样的错误。我不确定我做错了什么。

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()

例如,如果我们输入加布里埃尔;母鹿;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'

您正在覆盖光标c

c = int(input("Payment: "))

不要使用全局变量,而是将游标用作短活对象:

def insert_emp(conn, emp):  # This is used for inserting employees in the table
with conn:
cur = conn.cursor()
cur.execute("INSERT INTO employees VALUES (:first, :last, :pay)", {'first': emp.first, 'last': emp.last, 'pay': emp.pay})

相关内容

最新更新