OperationalError: not enough arguments for format string

OperationalError: not enough arguments for format string

我是运行以下代码:

#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()

我收到以下错误:

Traceback (most recent call last):
  File "interface.py", line 228, in <module>
    db.run()
  File "interface.py", line 219, in run
    actions[self.print_menu()-1]()
  File "interface.py", line 194, in insert
    self.cur.execute(query, params)
  File "build/bdist.macosx-10.6-intel/egg/pgdb.py", line 323, in execute
  File "build/bdist.macosx-10.6-intel/egg/pgdb.py", line 359, in executemany
pg.OperationalError: internal error in 'BEGIN': not enough arguments for format string

这让我感到困惑,因为当我打印参数和引用时,我可以看到元素的数量与 %s 标签的数量完全一样:

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

我做错了什么?参数应该和%s的一样多吧?

确保你没有转义字符串,如果你只是传递异常,你将改变传递值的顺序。数据库也会进行对话,所以无论如何都不需要 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

此外,这是我对同一问题的解决方案:

def db_insert(conn, cur, table, data):
    sql = ('INSERT INTO %s (' % table) + ', '.join(data.keys()) + ') VALUES(' + ', '.join(['?' for j in data.values()]) +')'

    cur.execute(sql, tuple(data.values()))
    lastid = cur.lastrowid
    conn.commit()

    return lastid

你可以这样使用它:

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
})

你有两个问题:

  • 您正在使用 positional 参数,每个 %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)