首页 > 解决方案 > 将字典或列表添加到 Sqlite3 - 给出错误操作参数必须是 str

问题描述

好的,我一般是 sqlite 和 python 的新手,所以请友好 =) 我有一本简单的字典 -

time = data[0]['timestamp']
price = data[0]['price']

myprice = {'Date':time,'price':price}

myprice 看起来像这样(时间是时间戳) -

{'Date': 1553549093, 'price': 1.7686}

我现在想将数据添加到 sqlite3 数据库......所以我创建了这个 -

#Create database if not exist...

db_filename = 'mydb_test.db'
connection = sqlite3.connect(db_filename)

#Get a SQL cursor to be able to execute SQL commands...

cursor = connection.cursor()

#Create table

sql = '''CREATE TABLE IF NOT EXISTS TEST
            (PID INTEGER PRIMARY KEY AUTOINCREMENT,
            DATE TIMESTAMP,
            PRICE FLOAT)'''

#Now lets execute the above SQL

cursor.execute(sql)


#Insert data in sql

sql2 =  ("INSERT INTO GBPCAD VALUES (?,?)", [(myprice['Date'],myprice['price'])])

cursor.execute(sql2)
cursor.commit()
connection.close()

但是当执行这段代码时,我得到ValueError: operation parameter must be str

我究竟做错了什么?

标签: sqlitepython-3.6

解决方案


insert将语句的参数传递给execute()

sql2 =  "INSERT INTO GBPCAD (DATE, PRICE) VALUES (?,?)"
cursor.execute(sql2, (myprice['Date'], myprice['price']))

还要在插入语句中包含列的名称。


推荐阅读