'How do I update a SQLite3 database in Python with user input?
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
Solution 1:[1]
as you mentioned you can use "?" sign as a placeholder for variables which would look like this:
sql = "UPDATE bank_accs SET amount = ? WHERE rowid = 1"
c.execute(sql, (current_acc,))
sql = "UPDATE bank_accs SET amount = ? WHERE rowid = 2"
c.execute(sql, (bills_acc,))
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Swagnar |
