卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章64334本站已运行4115

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

不知道为什么在尝试使用 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')
卓越飞翔博客
上一篇: 在Go中从Kafka读取并写入PostgreSQL时如何处理错误?
下一篇: 使用日期时间和删除经过的时间解析股票行情
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏