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

王林
发布: 2024-02-09 22:24:04
转载
682人浏览过

不知道为什么在尝试使用 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 的数据类型,但这仅更改了错误


正确答案


还有很多需要改进的地方。我只做了一些小改动,你可以进一步改进。始终插入元组。更改主键是可能的,但不是那么容易,谷歌一下。首次初始化值后请求新值。也请仔细阅读上面的评论!

阿里云-虚拟数字人
阿里云-虚拟数字人

阿里云-虚拟数字人是什么? ...

阿里云-虚拟数字人 2
查看详情 阿里云-虚拟数字人
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中文网其它相关文章!

最佳 Windows 性能的顶级免费优化软件
最佳 Windows 性能的顶级免费优化软件

每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。

下载
来源:stackoverflow网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
热门推荐
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号