使用 sqlite3 从表中取回数据并根据条件返回#results的函数仅返回零。通过Visual Studio运行#function会带来预期的结果,但是#当我尝试从终端运行它时,它将表解释为空列表。
import sqlite3
con = sqlite3.connect('test2.db')
cur = con.cursor()
小表来说明问题。表格输出为[('Jane', 300.0), ('Joe', 100.0), ('Joe', 50.0)]
total_bal = """SELECT name, amount FROM customers2"""
user_name = input("What is your name? ")
def account_balance(name):
cur.execute(total_bal)
table = cur.execute(total_bal)
total = 0
name = user_name
for t in table:
if t[0] == name:
total += t[1]
return total
print(account_balance(user_name))
期望返回150 if user_name input = 'Joe' or 300 if 'Jane'
答案 0 :(得分:0)
实际上,您可以对查询执行此操作,并且完全避免使用帐户余额功能。
statement = "SELECT name, account FROM customers2 WHERE name = ?;"
name = input("Enter your name: ")
cur.execute(statement, (str(name),))
results = cur.fetchone()
if results:
print(f"Name: {results[0]}\nAccount Balance: {results[1]}"
else:
print("Your name is not in the database")