sqlite3.OperationalError: unrecognized token: ":"

本文详细介绍了在Python使用SQLite3模块时遇到的SQL执行错误,从原始代码中的问号风格参数化转换为命名风格参数化,成功解决了未识别符号的错误,最终代码实现正确执行SQL查询并返回预期结果。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

看《集体智慧编程》第四章 中定义getentryid()报了 sqlite3.OperationalError: unrecognized token: ":" 错误。

 def getentryid(self,table,field,value,createnew=True):
    cur=self.con.execute(
    "select rowid from %s where %s=%s" % (table,field,value))
    res=cur.fetchone()
    if res==None:
      cur=self.con.execute(
      "insert into %s (%s) values (%s)" % (table,field,value))
      return cur.lastrowid
    else:
      return res[0] 

然后想起来,好像把
cur=self.con.execute("select rowid from %s where %s=%s" % (table,field,value))
中第三个%s的引号去掉了,结果加上引号好像之前报了个什么引号找不到还是无法识别的错误。

然后查了好多,最后看文档

execute(sql[parameters])

Executes an SQL statement. The SQL statement may be parameterized (i. e. placeholders instead of SQL literals). The sqlite3 module supports two kinds of placeholders: question marks (qmark style) and named placeholders (named style).

Here’s an example of both styles:

import sqlite3

con = sqlite3.connect(":memory:")
cur = con.cursor()
cur.execute("create table people (name_last, age)")

who = "Yeltsin"
age = 72

# This is the qmark style:
cur.execute("insert into people values (?, ?)", (who, age))

# And this is the named style:
cur.execute("select * from people where name_last=:who and age=:age", {"who": who, "age": age})

print(cur.fetchone())

execute() will only execute a single SQL statement. If you try to execute more than one statement with it, it will raise a Warning. Use executescript() if you want to execute multiple SQL statements with one call.


按照named style 把原来的代码改成了(insert改qmark style 还是报错不知道为什么 = =)

    def getentryid(self, table, field, value, createnew = True):
        cur = self.con.execute("select rowid from %s where %s = :value " % (table, field), {"value": value})
        res = cur.fetchone()
        if res is None:
            cur = self.con.execute("insert into %s (%s) values (:value)" % (table, field), {"value": value})
            return cur.lastrowid
        else:
            return res[0]


哈哈,没报错~\(≧▽≦)/~啦啦啦


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值