首頁  >  文章  >  後端開發  >  不知道為什麼在嘗試使用 f 字串執行 SQL UPDATE 查詢時會出現語法錯誤

不知道為什麼在嘗試使用 f 字串執行 SQL UPDATE 查詢時會出現語法錯誤

王林
王林轉載
2024-02-09 22:24:04616瀏覽

不知道为什么在尝试使用 f 字符串运行 SQL UPDATE 查询时出现语法错误

問題內容

我正在嘗試執行基本的sql 查詢來更新名為bartonhill 的資料庫中schoolnum 的值,使用f 字串將值放入

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())

但是,如果我輸入我的名字 ollie(作為 firsname 存在於資料庫中),則執行此程式碼會出現錯誤「 sqlite3.operationalerror:near「ollie」:語法錯誤」

我嘗試更改 name 和 new_number 的資料類型,但這只更改了錯誤


#正確答案


還有很多需要改進的地方。我只做了一些小改動,你可以進一步改進。始終插入元組。更改主鍵是可能的,但不是那麼容易,谷歌一下。首次初始化值後請求新值。也請仔細閱讀上面的評論!

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())

輸出:

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

或另一個選擇:

c.execute("select schoolnum, lastname from bartonhill where firstname = ?;", (firstname,))
print(c.fetchone())

僅給您特定值:

(20000, 'Burgess')

以上是不知道為什麼在嘗試使用 f 字串執行 SQL UPDATE 查詢時會出現語法錯誤的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:stackoverflow.com。如有侵權,請聯絡admin@php.cn刪除