这是我正在查看的Tutorialspoint.com代码。
#!/usr/bin/python
import sqlite3
conn = sqlite3.connect('test.db')
conn.execute('''CREATE TABLE COMPANY
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES (1, 'Paul', 32, 'California', 20000.00 )");
conn.commit()
conn.close()
我如何将一个整数变量添加到其中一个值,比方说AGE。例如,我试过这个但是我得到了一个值错误:
p=32
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES(1,'Paul',?,'California',20000.00)",p)
我是否必须将所有变量存储在列表中,然后像这样添加到数据库中?
list = [(1,'Paul',32,'California',20000.00)]
for item in list:
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES(?,?,?,?,?)",item)
答案 0 :(得分:2)
将参数值传递为list或tuple:
p = 32
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
VALUES(1,'Paul',?,'California',20000.00)", [p])
.execute(operation [, parameters])
... 参数可以作为序列或映射提供并将被绑定 操作中的变量。 ...