Why my code gives error: "sqlite3.OperationalError: no such column: "?
Why my code gives error: "sqlite3.OperationalError: no such column: "?
为什么我的程序给我错误提示我的 Sqlite3
Tasks
-table 中不存在该列?这是我的代码:
class Db:
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
def create_table(self):
create_Tasks_table = '''CREATE TABLE Tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
notes TEXT,
deadline TEXT,
state INTEGER);'''
self.cursor.execute(create_Tasks_table)
self.conn.commit()
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = """INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?), (title, notes, deadline, state)"""
self.cursor.execute(add_to_Tasks_table)
self.conn.commit()
if __name__ == "__main__":
db = Db()
db.create_table()
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
我与 DB Browser for SQlite
确认 table 已正确创建且列名正确,如图所示:
编辑:这是完整的错误:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\project\mytest.py", line 91, in <module>
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
File "C:\Users\User\PycharmProjects\project\mytest.py", line 36, in add_task
self.cursor.execute(add_to_Tasks_table)
sqlite3.OperationalError: no such column: title
您的代码的问题在于您包含了包含您在 sql 语句中传递的参数的元组。
它应该作为 cursor.execute()
:
的第二个参数
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = "INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?)"
self.cursor.execute(add_to_Tasks_table, (title, notes, deadline, state))
self.conn.commit()
为什么我的程序给我错误提示我的 Sqlite3
Tasks
-table 中不存在该列?这是我的代码:
class Db:
conn = sqlite3.connect('database.db')
cursor = conn.cursor()
def create_table(self):
create_Tasks_table = '''CREATE TABLE Tasks (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
notes TEXT,
deadline TEXT,
state INTEGER);'''
self.cursor.execute(create_Tasks_table)
self.conn.commit()
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = """INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?), (title, notes, deadline, state)"""
self.cursor.execute(add_to_Tasks_table)
self.conn.commit()
if __name__ == "__main__":
db = Db()
db.create_table()
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
我与 DB Browser for SQlite
确认 table 已正确创建且列名正确,如图所示:
编辑:这是完整的错误:
Traceback (most recent call last):
File "C:\Users\User\PycharmProjects\project\mytest.py", line 91, in <module>
db.add_task("title1", "Note1", "2021-10-30 18:00:00")
File "C:\Users\User\PycharmProjects\project\mytest.py", line 36, in add_task
self.cursor.execute(add_to_Tasks_table)
sqlite3.OperationalError: no such column: title
您的代码的问题在于您包含了包含您在 sql 语句中传递的参数的元组。
它应该作为 cursor.execute()
:
def add_task(self, title, notes, deadline):
state = 0
add_to_Tasks_table = "INSERT INTO Tasks (title, notes, deadline, state) values (?, ?, ?, ?)"
self.cursor.execute(add_to_Tasks_table, (title, notes, deadline, state))
self.conn.commit()