如何使用用户输入更新Python中的SQLite3数据库?
我正在尝试在Python中创建一个个人预算计划,并且在用户的输入中更新当前银行余额的数据库遇到了困难。我将用户输入(现金余额)存储在变量中,但我似乎无法将变量输入到数据库中。我没有收到任何错误消息,但是我只能将变量名称存储在数据库中,而不是变量代表的用户输入的金额。
这是我的代码的简化版本:
# import modules
import sqlite3
# user input
current_acc = float(input("Natwest Current A/C: "))
bills_acc = float(input("Natwest Bills A/C: "))
# update database
conn = sqlite3.connect("databases/bank_accs.db")
c = conn.cursor()
c.execute("""UPDATE bank_accs SET amount = 'current_acc' WHERE rowid = 1"""),
c.execute("""UPDATE bank_accs SET amount = 'bills_acc' WHERE rowid = 2""")
# query database
c.execute("SELECT rowid, * FROM bank_accs")
items = c.fetchall()
for item in items:
print(item)
# commit and close
conn.commit()
conn.close()
我已经广泛地搜索了这个问题,但似乎找不到答案。我发现的唯一真正的线索是在堆栈溢出上,建议将变量名称替换为占位符的“?”,但是,尚不清楚如何用可变值代替占位符。
我真的很感谢您对我在这里做错的事情的任何帮助或见解。我是编码的新手,这是我在这里的第一个问题,希望我的问题有意义。
谢谢,保罗
I am trying to create a personal budget program in Python and I am having trouble updating my database of current bank balances with input from the user. I store the user inputs (cash balances) in variables but I can't seem to get the input from the variables into the database. I don't get any error messages but I can only store the variable names in the database, rather than the amounts from the user input that the variables represent.
Here is a simplified version of my code:
# import modules
import sqlite3
# user input
current_acc = float(input("Natwest Current A/C: "))
bills_acc = float(input("Natwest Bills A/C: "))
# update database
conn = sqlite3.connect("databases/bank_accs.db")
c = conn.cursor()
c.execute("""UPDATE bank_accs SET amount = 'current_acc' WHERE rowid = 1"""),
c.execute("""UPDATE bank_accs SET amount = 'bills_acc' WHERE rowid = 2""")
# query database
c.execute("SELECT rowid, * FROM bank_accs")
items = c.fetchall()
for item in items:
print(item)
# commit and close
conn.commit()
conn.close()
I have googled this problem extensively but can't seem to find an answer. The only real clue I found was on Stack Overflow where it was suggested that the variable names should be replaced by placeholders '?', however it wasn't clear about how you replace the placeholders with the variable values.
I would really appreciate any help or insight into what I am doing wrong here. I am quite new to coding and this is my first question on here, I hope my question makes sense.
Thanks, Paul
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如您提到的,您可以使用“?”作为变量的占位符,这是这样:
as you mentioned you can use "?" sign as a placeholder for variables which would look like this: