操作错误:格式字符串的参数不足

2024-06-17 11:15:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在运行以下代码:

#converts strings that are ints to int.
for i,x in enumerate(values):
    try:
        values[i] = int(x)
    except:
        pass

# Fills values with NULLs if needed
if len(values) < no_of_columns:
    values = values + ["NULL"]*(no_of_columns-len(values))
print(values)

# Creates dict with params and values
params = {}
for i, x in enumerate(values):
    params[i] = x

query = "INSERT INTO {} VALUES ({});".format(table_name,",".join(['%s']*no_of_columns))

self.cur.execute(query, params)
self.print_answer()

结果是我得到了以下错误:

^{pr2}$

这让我很困惑,因为当我打印params和quote时,我可以看到元素的数量与%s标记的数量一样多:

params = {0: 22, 1: 'ehj', 2: 'NULL', 3: 'NULL'}
query = 'INSERT INTO books VALUES (%s,%s,%s,%s);'

我做错什么了?参数值应该与%s的相同,对吗?在


Tags: columnsofnoinforlenifwith
2条回答

你有两个问题:

  • 您使用的是位置参数,每个%s都将与cursor.execute()的第二个参数中的一个连续值相匹配,这应该是一个列表或元组。您希望使用values而根本不构建params字典。

  • 不应将字符串NULL用于空值,而应使用None;字符串将按字面意思插入(因此不是SQL NULL,而是*string值'NULL'),Python值None表示实际的空值。在

    或者,您可以在生成的INSERT语句中用NULL值替换参数(因此生成的SQL具有NULL文本,而不是参数。

我也不会使用笼统的except:语句;您正在使所有错误静音。抓住ValueError

#converts strings that are ints to int.
for i,x in enumerate(values):
    try:
        values[i] = int(x)
    except ValueError:
        pass

# Fills values with NULLs if needed
values += [None] * (no_of_columns - len(values))

query = "INSERT INTO {} VALUES ({});".format(
    table_name, ",".join(['%s'] * no_of_columns))

self.cur.execute(query, values)

确保没有转义字符串,如果只传递异常,则会更改传递值的顺序。另外,数据库也会进行对话,因此不需要int()。在

#converts strings that are ints to int.
for i,x in enumerate(values):
    try:
        values[i] = int(x)
    except:
        values[i] = x # see note above

同样,我的解决方案如下:

^{pr2}$

你可以这样使用它:

conn = sqlite3.connect(DB_PATH)
cur = conn.cursor()

db_insert(conn, cur, 'ig_media', {
   'user_id': uid,
   'media_id': mid,
   'like_date': arrow.now().timestamp
})

相关问题 更多 >