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

如何提取SQLite数据库查询结果并打印?后续需与用户输入对比

解决SQLite查询结果提取与用户输入对比的问题

Hey there! Let's sort out your SQLite query issue and get that answer comparison working smoothly.

问题所在

Your current code stores the cursor object (returned by c.execute()) in DBF1 and prints it directly—this is why you’re seeing something like <sqlite3.Cursor object at 0x...> instead of the actual question text. The cursor is just a pointer to the result set; you need to use a fetch method to pull out the real data.

修改后的完整代码(含结果提取与对比逻辑)

Here’s how to properly fetch the random question, print it, and compare the user’s input to the correct answer:

import sqlite3 
conn = sqlite3.connect('Karteikarten.db') 
c = conn.cursor() 

# 同时查询问题和对应的正确答案(方便后续对比)
c.execute('SELECT Frage, Antwort FROM Karteikarten ORDER BY RANDOM() LIMIT 1')
# 获取单条记录,返回格式为元组:(问题内容, 正确答案内容)
card_data = c.fetchone()

if card_data:
    # 从元组中提取问题和正确答案
    question = card_data[0]
    correct_answer = card_data[1]
    
    # 打印提取到的问题
    print(f"Frage: {question}")
    
    # 收集用户输入并对比答案
    user_answer = input("Gib deine Antwort ein: ")
    
    # 忽略大小写和前后空格,提升用户体验
    if user_answer.strip().lower() == correct_answer.strip().lower():
        print("Perfekt! Das ist die richtige Antwort 🎉")
    else:
        print(f"Leider nicht korrekt. Die richtige Antwort lautet: {correct_answer}")
else:
    print("Es gibt noch keine Karteikarten in der Datenbank. Füge zuerst einige hinzu!")

# 查询操作不需要commit(),只有修改数据(插入/更新/删除)时才需要执行commit
conn.close()

关键细节说明

  • fetchone(): This method retrieves the first row of the result set as a tuple. Since we used LIMIT 1, it gives us exactly the random flashcard we need.
  • 字段提取: The tuple indexes [0] and [1] map to the Frage and Antwort columns we selected in the query.
  • 友好对比: Using strip() and lower() ensures the comparison ignores accidental extra spaces and case differences, making the interaction more user-friendly.
  • 空数据库处理: The if card_data check prevents the script from crashing if there are no flashcards stored yet.

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.09 18:22:52