not sure why I get a syntax error when trying to run a SQL UPDATE query using f strings

278 Views Asked by At

I am trying to run a basic SQL query to UPDATE the value for schoolNum from a database called bartonHill, using f strings to put the values in

import sqlite3
name = [input('enter your firstname: ')]


conn = sqlite3.connect('revision.db')
c = conn.cursor()

# create table
c.execute('''CREATE TABLE IF NOT EXISTS bartonHill (
    firstName TEXT NOT NULL,
    lastName TEXT NOT NULL,
    schoolNum INTEGER NOT NULL PRIMARY KEY
)''')

conn.commit()

c.execute("INSERT INTO bartonHill VALUES ('Ollie','Burgess','20314')")
conn.commit()

new_number = tuple[(int(input('enter your new school number')))]
c.execute(f"UPDATE bartonHill set schoolNum = '{new_number}' WHERE firstName = '{name}'")
conn.commit
c.execute('SELECT lastName, schoolNum FROM bartonHill WHERE firstName = (?)',name)
print(c.fetchall())

However running this code gives me the error " sqlite3.OperationalError: near "Ollie": syntax error " if i input my name Ollie (which exists inside the database as a firsName)

I have tried changing the datatype of name and new_number but this only changed the error

1

There are 1 best solutions below

0
Hermann12 On BEST ANSWER

There are a lot of point to improve. I made some small changes only, that you can further improve. INSERT always tuple. Change a PRIMARY KEY is possible, but not so easy, google for that. Ask for new values after first initialization of your values. Read the comments above carefully, too!

import sqlite3

conn = sqlite3.connect('revision.db')
c = conn.cursor()

# create table
c.execute('''CREATE TABLE IF NOT EXISTS bartonHill (
    id integer PRIMARY KEY AUTOINCREMENT,
    schoolNum integer NOT NULL,
    firstName TEXT NOT NULL,
    lastName TEXT NOT NULL   
)''')
conn.commit()

c.execute("INSERT INTO bartonHill (schoolNum,firstName,lastName) VALUES (?,?,?); ", (20314, 'Ollie','Burgess'))
conn.commit()

# Ask for changes here
firstname = input('enter your firstname: ')
lastname = input('enter your lastname: ')
new_number = int(input('enter your new school number: '))

c.execute("UPDATE bartonHill set schoolNum = ? WHERE firstName = ?;", (new_number, firstname))
conn.commit

c.execute("SELECT * FROM bartonHill WHERE firstName = ?;", (firstname,))
print(c.fetchall())

Output:

>>> enter your firstname: Ollie
>>> enter your lastname: Burgess
>>> enter your new school number: 20000
>>> [(1, 20000, 'Ollie', 'Burgess')]

or anoter SELECT:

c.execute("SELECT schoolNum, lastName FROM bartonHill WHERE firstName = ?;", (firstname,))
print(c.fetchone())

Gives you specific values only:

(20000, 'Burgess')