【问题标题】:Python doesn't commit data to SQLite database [closed]Python不会将数据提交到SQLite数据库[关闭]
【发布时间】:2020-08-25 07:16:18
【问题描述】:

每次我运行这段代码时,这段代码都应该将这两条记录插入并保存到我的数据库中,但它不起作用。

没有错误,一切正常,除了提交对数据库的更改,我不知道为什么。

import sqlite3

conn = sqlite3.connect('SQLite_Python.db')
c = conn.cursor()

c.execute("""DROP TABLE IF EXISTS expenses;""")
c.execute("""CREATE TABLE expenses (
            name text,
            amount text,
            date_of_expense text,
            category text,
            notes text
            )""")

def insert_expense(exp):
    with conn:
        c.execute("INSERT INTO expenses VALUES (?, ?, ?, ?, ?)", 
            (exp.name, exp.amount, exp.date_of_expense, exp.category, exp.notes))


def get_all_expenses():
    c.execute("SELECT * FROM expenses")
    return c.fetchall()

exp1 = Expense('apple', '5.50', '02:12:1202','food', '-')
exp2 = Expense('orange', '9.90', '05:02:1892', 'food', '-')

insert_expense(exp1)
insert_expense(exp2)

exps = get_expense_by_category('food')
print(exps)

conn.commit()
conn.close()

我的目标是将记录保存到数据库中,当我再次打开此数据库时,我想查看旧记录。

【问题讨论】:

  • 如果您每次都有“DROP TABLE IF EXISTS costs”,您希望如何查看旧记录?
  • 天哪,我不知道为什么我没有注意到.. 非常感谢

标签: python sql database sqlite


【解决方案1】:

删除“如果存在费用则删除表”;)

【讨论】:

    猜你喜欢
    • 2018-05-18
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-10
    • 2015-10-17
    相关资源
    最近更新 更多