看《集体智慧编程》第四章 中定义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]