sqlite - 将字典或列表添加到 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
我究竟做错了什么?
解决方案
insert
将语句的参数传递给execute()
:
sql2 = "INSERT INTO GBPCAD (DATE, PRICE) VALUES (?,?)"
cursor.execute(sql2, (myprice['Date'], myprice['price']))
还要在插入语句中包含列的名称。
推荐阅读
- c# - 无法将“System.Collections.Generic.List`1 类型的对象转换为 System.Windows.Forms.BindingSource”类型
- r - 从一系列注视计算首次注视时间、首次注视持续时间和访问持续时间(眼动追踪;R)
- php - 我将如何更新这些规则以便两者都可以在 .htaccess 中运行?
- google-apps-script - Google Sheet 加速循环
- java - 我如何访问对象 o 的吸气剂
- debugging - vmlaunch 后调试虚拟机
- python - FileNotFoundError:[Errno 2] 没有这样的文件或目录:'netsh'
- python-3.x - 使用 tkinter gui 从 python 3.8.5 编译的 Exe 在 Windows10 上引发致命错误
- middleware - 找不到满足 CORSMiddleware 要求的版本(来自版本:)没有为 CORSMiddleware 找到匹配的发行版
- python - 在 Matplotlib 画布上绘制单独的线并将坐标写入数据框