0

这是我正在查看的来自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)
4

1 回答 1

2

Pass parameter value as list or tuple:

p = 32
conn.execute("INSERT INTO COMPANY (ID,NAME,AGE,ADDRESS,SALARY) \
             VALUES(1,'Paul',?,'California',20000.00)", [p])

According to the DB API specification:

.execute(operation [, parameters])

... Parameters may be provided as sequence or mapping and will be bound to variables in the operation. ...

于 2013-10-12T04:31:33.140 回答