我想将长度可变的表插入到sqlite数据库中,但收到一个错误消息:提供的绑定数量不正确

2024-06-25 23:44:30 发布

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

因为我想插入大小不同的表,所以我需要能够在insert语句中使用字符串变量,例如:

numvals = '?,?'
vals = 'delays_values[0], delays_values[1]'
converted_valz = 'ID int ,Description text'

c.execute("CREATE TABLE DELAYS ("+converted_valz+")")
c.execute("INSERT INTO DELAYS VALUES ("+numvals+" )", (vals))

然而,这给了我前面提到的错误,它确切地说:sqlite3.ProgrammingError:提供的绑定数量不正确。当前语句使用19个,提供了349个

出于某种原因,如果我用它实际包含的硬编码值替换VAL,那么它实际上是工作的,但是我被迫硬编码值,这违背了所有这些的目的。请帮忙

numvals = '?,?'
vals = 'delays_values[0], delays_values[1]'
converted_valz = 'ID int ,Description text'

c.execute("CREATE TABLE DELAYS ("+converted_valz+")")
c.execute("INSERT INTO DELAYS VALUES ("+numvals+" )", (delays_values[0], delays_values[1]))


Tags: textidexecutecreatetabledescription语句int
1条回答
网友
1楼 · 发布于 2024-06-25 23:44:30

这可能是一个过于简化的问题,可能会在以后引起问题,但一个简单的解决方法是在最后使用eval(vals)vals字符串求值:

import sqlite3
conn = sqlite3.connect('example.db')

c = conn.cursor()

delays_values = (1,2)

numvals = '?,?'
vals = 'delays_values[0], delays_values[1]'
converted_valz = 'ID int ,Description text'

c.execute("CREATE TABLE DELAYS ("+converted_valz+")")

c.execute("INSERT INTO DELAYS VALUES ("+numvals+" )", eval(vals))

不知道为什么vals是一个字符串开头,但老实说

相关问题 更多 >