我希望将 python 上的用户输入存储到 sqlite 数据库中。
import sqlite3
calories1=["please"]
food1=["please"]
time1=["please"]
try:
sqliteConnection = sqlite3.connect('NEA.db')
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
insertQuery = """INSERT INTO foodEntry(
calories, food, timing)
VALUES
(?,?,?)""".format(calories1, food1, time1)
count = cursor.execute(insertQuery)
sqliteConnection.commit()
print("Record inserted successfully into table ", cursor.rowcount)
cursor.close()
except sqlite3.Error as error:
print("Failed to insert data into sqlite table", error)
finally:
if sqliteConnection:
sqliteConnection.close()
print("The SQLite connection is closed")
我不断收到错误消息,请帮助,因为这是最终项目,谢谢。
我不明白你为什么把
"please"
字符串放在列表中;那不是你想要的。此外,连接到数据库并再次关闭它的单独代码是没有意义的。
你的
try/except
块会适得其反。如果失败,无论如何都无法继续操作。规则#1 是“永远不要检查您不准备处理的异常”。如果您遇到数据库错误,回溯将为您提供解决该错误所需的信息。所以,不要抓住它。
正如 Zorgoth 指出的,最大的问题是你不使用
.format
来进行替换。您将变量作为第二个参数传递给 .execute
调用。
这就是你所追求的:
import sqlite3
calories1="please"
food1="please"
time1="please"
sqliteConnection = sqlite3.connect('NEA.db')
cursor = sqliteConnection.cursor()
print("Successfully Connected to SQLite")
insertQuery = """INSERT INTO foodEntry(calories, food, timing)
VALUES (?,?,?)"""
count = cursor.execute(insertQuery, (calories1, food1, time1))
sqliteConnection.commit()
print("Record inserted successfully into table ", cursor.rowcount)
cursor.close()
sqliteConnection.close()
如文档中所述,查询中的占位符替换是在没有 .format 的情况下完成的,而是在 .execute 方法中完成的,因此语法为:
insertQuery = """INSERT INTO foodEntry(
calories, food, timing)
VALUES
(?,?,?)"""
count = cursor.execute(insertQuery, (calories1, food1, time1))