如何在sqlite3请求python中插入变量

时间:2018-06-09 19:33:56

标签: python variables sqlite

逗人,

如何检查数据库中的pos_cli是否等于变量pos_id?现在使用下面的代码我得到以下错误

cur.execute("CREATE TABLE IF NOT EXISTS Magnit_Coor (pos_cli INTEGER PRIMARY KEY, lat INTEGER, long INTEGER);")
cur.execute('SELECT * FROM Magnit_pos')
data = cur.fetchall()
while True:
    for coo in data:
        full_add = coo[6:11]
        pos_id = coo[0]
        print (pos_id)
        yand_add = ", ".join(full_add)
        g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_Coor WHERE pos_cli = (?))',pos_id)
        g = cur.fetchone()[0]

错误

10001
Traceback (most recent call last):
  File "geoco.py", line 17, in <module>
    g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_pos WHERE pos_cli = (?))',pos_id)
ValueError: parameters are of unsupported type

创建Magnit_pos表和pos_cli的初始代码,尤其是

cur.execute("DROP TABLE IF EXISTS Magnit_Pos;")
cur.execute(
    "CREATE TABLE Magnit_Pos (pos_cli INTEGER PRIMARY KEY, magnit_name TEXT, codesfa TEXT, codewsot TEXT, pos_sap TEXT, source_dc TEXT, zip TEXT, region TEXT, area TEXT, city TEXT, street TEXT, house TEXT, build TEXT);")

with open('magnit.csv') as csvfile:
    magnit = csv.reader(csvfile, delimiter=';')
    print(magnit)
    for row in magnit:
        print(row[0])
        # to_db = [unicode(row[0], "utf8"), unicode(row[1], "utf8")]
        cur.execute("INSERT INTO Magnit_Pos (pos_cli, magnit_name, codesfa, codewsot, pos_sap, source_dc, zip, region, area, city, street, house, build) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?);", row)

1 个答案:

答案 0 :(得分:1)

来自python&#39; s sqlite3 documentation(强调我的):

  

放?作为占位符,无论您想要使用哪个值,然后提供 值元组 作为游标执行()方法的第二个参数。

所以你应该使用:

    g = cur.execute('SELECT EXISTS (SELECT * FROM Magnit_Coor WHERE pos_cli = (?))',(pos_id,))