OperationalError:格式字符串的参数不足

时间:2015-09-26 18:51:33

标签: python formatting pygresql

我正在运行以下代码:

#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相同,对吧?

2 个答案:

答案 0 :(得分:1)

你有两个问题:

  • 您正在使用位置参数,每个%s会将第二个参数中的连续值与cursor.execute()匹配,该值应为列表或元组在这里。您想使用values而不是构建params字典。

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

    或者,您可以在生成的NULL语句中用INSERT值替换参数(因此生成的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)

答案 1 :(得分:0)

确保不转义字符串,如果只是传递异常,则会更改传递的值顺序。此外,数据库也会进行对话,因此无论如何都不需要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
})