You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python向SQLite表插入数据失败、程序无法持续运行问题求解

问题排查与解决方案

一、SQLite 数据不更新的核心原因

你的插入逻辑存在语法写法错误,直接导致INSERT语句根本没有被执行:

# 错误写法:行尾没有括号,这行仅引用了cursor.execute方法,没有发起调用
cursor.execute
# 下方括号包裹的SQL和参数是独立的元组表达式,没有传入execute方法,不会被执行
(""" INSERT INTO Books (id, title, year) VALUES (?,?,?)  
   """, (book_id, book_title, book_year))

这种写法下没有任何SQL被发送到数据库执行,后续的conn.commit()自然没有任何事务可提交,数据库不会有任何数据写入。
另外有个非功能性的小问题:你连接数据库时写的文件名是Books,生成的是无后缀文件,后续排查时很容易找不到对应库文件,建议改成Books.db符合通用命名习惯。

二、实现程序持续运行的方法

你当前的代码只会接收一次用户输入,执行完对应分支就直接走到关闭连接、退出程序的逻辑。要实现循环展示操作菜单,只需要把交互逻辑套入while True无限循环,额外增加一个退出选项触发循环break即可。

修正后可直接运行的代码

import sqlite3
# 建立数据库连接
conn = sqlite3.connect("Books.db")
cursor = conn.cursor()

# 初始化表结构
cursor.execute("""CREATE TABLE IF NOT EXISTS Books(
   id INT PRIMARY KEY,
   title TEXT,
   year INT);
""")
conn.commit()

# 循环展示操作菜单
while True:
    user_input = input("""Dear User, you have the following options (case sensitive):
    1. INSERT
    2. SHOW BOOKS
    3. EXIT
Please insert your command here: <<< """)      

    if user_input == "1. INSERT":
        book_id = int(input("Book id: "))
        book_title = input("Book title: ")
        book_year = int(input("Book year of publication: "))
        # 注意execute后直接跟括号,不要随意断行;如果要换行写参数,需要把括号留在上一行行尾
        cursor.execute(
            """INSERT INTO Books (id, title, year) VALUES (?,?,?)""",
            (book_id, book_title, book_year)
        )
        conn.commit()
        print("Book inserted successfully!")

    elif user_input == "2. SHOW BOOKS":
        cursor.execute("SELECT * FROM Books;")
        all_results = cursor.fetchall()
        print("当前藏书列表:")
        for book in all_results:
            print(f"ID: {book[0]} | 书名: {book[1]} | 出版年份: {book[2]}")

    elif user_input == "3. EXIT":
        print("程序即将退出")
        break

    else:
        print("Not a valid command. Try again! It's all case sensitive in Python, u know...")

# 所有操作结束、循环退出后再关闭数据库连接
if conn:
    conn.close()

其他优化提示

  • 你原代码中输入的book_id、book_year默认是字符串类型,和表结构定义的INT类型不匹配,插入时建议用int()做类型转换
  • 数据库连接不要在单次操作后关闭,要等整个程序完全退出前再关闭,否则循环内第二次操作数据库会抛出连接已关闭的异常
  • 原代码里有两处拼写笔误:comamnd应为command、succesfully应为successfully,不影响运行但建议修正

内容的提问来源于stack exchange,提问作者Catcher InTheRye

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 16:06:25