Home > Enterprise >  Update SQLite using Python using user input
Update SQLite using Python using user input

Time:08-21

Hi I want to be able to update the income of a specific record using the user input to find it. I can't seem to figure it out. I can only update the database using the following code below. I'm new to programming- have looked in books and online and can't seem to find the solution.

What do I need to do to the code below to be able to do this.

import sqlite3
from sqlite3 import Connection

conn: Connection = sqlite3.connect('tax1.db')
c = conn.cursor()
c.execute("UPDATE tax SET income = 10000 WHERE customerID = 1")
conn.commit()

CodePudding user response:

From this thread use a parameterised SQL query, e.g.

import sqlite3
from sqlite3 import Connection

customer_id = input("Enter the customer ID: ")
new_income  = input("Enter the income: ")

conn = sqlite3.connect('tax1.db')
c = conn.cursor()
c.execute("UPDATE tax SET income = ? WHERE customerID = ?",(new_income, customer_id))

See also this Python 3.9 documentation on the sqlite3 module which says:

use the DB-API’s parameter substitution. To insert a variable into a query string, use a placeholder in the string, and substitute the actual values into the query by providing them as a tuple of values to the second argument of the cursor’s execute() method. An SQL statement may use one of two kinds of placeholders: question marks (qmark style) or named placeholders (named style)

  • Related