【问题标题】:Dynamically Inserting into a Sqlite Database errors动态插入到 Sqlite 数据库错误
【发布时间】:2017-06-03 05:30:51
【问题描述】:

我有以下代码

cur.executemany("INSERT INTO "+tablename+" (name,"+item+") VALUES(?,?)",(data,))

data动态插入值 现在我有两个问题: 如果我使用 VALUES(?,?)",(data)) 的语法而不使用 , after data 我会收到这个错误

Error Incorrect number of bindings supplied. The current statement uses 2, and there are 4 supplied.:

这只能通过使用VALUES(?,?)",(data,)), 的语法来解决

它解决了这个问题,数据被插入到表中。 但它产生了另一个问题,我无法查询数据库并使用类似

cursor = cur.execute("select * from "+tablename+" where name="+name+"")

我会得到这个错误:

Error no such column: deek:

我不知道如何使用上述语法查询数据库。

我从上面得到了上面的语法 sqlite3.ProgrammingError: Incorrect number of bindings supplied. The current statement uses 1, and there are 74 supplied

完整代码供参考:

import sqlite3
import sys
tablename='asfoor'
table_data=['Name','a','b','c']

try:
    con = sqlite3.connect('dbtrials.db')
    cur = con.cursor()
    cur.execute("DROP TABLE IF EXISTS "+tablename+"")
    cur.execute("CREATE TABLE "+tablename+" (ID INTEGER PRIMARY KEY AUTOINCREMENT ,Name TEXT, "+table_data[1]+" TEXT, "+table_data[2]+" TEXT, "+table_data[3]+" TEXT )")



    name='deek'
    item='a'
    data=[name,item]
    cur.executemany("INSERT INTO "+tablename+" (name,"+item+") VALUES(?,?)",(data,))
    cursor = cur.execute("select * from "+tablename+" where name="+name+"")
    for row in cursor  :
              print(row)


except sqlite3.Error as e:

    print ("Error %s:" % e.args[0])
    sys.exit(1)

finally:

    if con:
        con.close()

【问题讨论】:

  • 它是一样的,如果我使用 VALUES(?,?)",(name,item)) 我仍然得到同样的错误The current statement uses 2, and there are 4 supplied

标签: python database sqlite


【解决方案1】:

错误的原因是您忘记在字符串周围加上引号。应该是:

cursor = cur.execute("select * from "+tablename+" where name='"+name+"'")

但最好使用参数化查询:

cursor = cur.execute("select * from "+tablename+" where name= %s", (name,))

【讨论】:

    【解决方案2】:

    executemany 期望 序列或映射的迭代器 作为第二个参数。 您的输入应如下所示:data = [[name, item]]

    所以你期望的查询:

    1. deek , a (2 args)

    如果没有内部列表,它将字符串作为字符序列,因此您的查询是:

    1. deek(4 个参数)

    2. a (1 arg)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-10-30
      • 1970-01-01
      • 1970-01-01
      • 2020-07-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多