You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用TraderMade SDK存数据至SQLite遇OperationalError:date列不存在

问题描述

尝试通过TraderMade Python SDK获取2022年全年EURUSD货币数据,并存储到已创建好的SQLite数据库(表eurusd含date、open、high、low、close列)中。编写的代码如下:

conn = db.connect("MarketData.db")
c = conn.cursor()

def data():
    tm.set_rest_api_key([MY API KEY])
    request = tm.timeseries(
        currency='EURUSD',
        start="2022-01-01",
        end="2022-12-31",
        interval="daily",
        fields=["open", "high", "low", "close"]
        )
    print(request)
    stmt = '''INSERT INTO eurusd VALUES (?,?,?,?,?), (date, open, high, low, close)'''
    c.executemany(stmt, request)
    return

data()
conn.commit()
print('complete')

数据能正常拉取(request打印结果正常),但运行代码时出现SQLite OperationalError,提示不存在date列,而数据库中确实存在该列。

问题分析与解决

核心问题:INSERT语句语法错误

原代码中的INSERT语句完全不符合SQL语法规范:

INSERT INTO eurusd VALUES (?,?,?,?,?), (date, open, high, low, close)

这行代码错误混合了两种INSERT写法,导致SQL解析器无法正确识别列名和值的对应关系,进而误判date为不存在的列。正确的INSERT写法有两种:

  1. 不指定列名(要求值的顺序与表列顺序完全一致):
    INSERT INTO eurusd VALUES (?, ?, ?, ?, ?)
    
  2. 指定列名(更安全,无需严格匹配表列顺序):
    INSERT INTO eurusd (date, open, high, low, close) VALUES (?, ?, ?, ?, ?)
    

次要问题:数据结构可能不匹配

虽然你说request打印正常,但需要确认返回的每条数据是否包含date字段(原代码fields参数只指定了open/high/low/close,部分API需要显式指定date才会返回)。如果request是字典列表格式,需要将其转换为元组列表才能适配executemany的参数要求。

修正后的代码

conn = db.connect("MarketData.db")
c = conn.cursor()

def data():
    tm.set_rest_api_key([MY API KEY])
    # 显式添加date到fields,确保返回日期字段
    request = tm.timeseries(
        currency='EURUSD',
        start="2022-01-01",
        end="2022-12-31",
        interval="daily",
        fields=["date", "open", "high", "low", "close"]
        )
    print(request)
    # 使用指定列名的INSERT写法,语法正确且更清晰
    stmt = '''INSERT INTO eurusd (date, open, high, low, close) VALUES (?, ?, ?, ?, ?)'''
    # 如果request是字典列表,转换为元组列表
    data_tuples = [(item['date'], item['open'], item['high'], item['low'], item['close']) for item in request]
    c.executemany(stmt, data_tuples)
    return

data()
conn.commit()
# 关闭连接,避免资源泄漏
conn.close()
print('complete')

额外提示

  • 执行数据库操作后记得关闭连接,避免资源占用;
  • 可以添加异常捕获,方便排查后续可能出现的问题;
  • 确认eurusd表的列顺序与你插入值的顺序一致(如果使用不指定列名的写法)。

内容的提问来源于stack exchange,提问作者jbaker3004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 00:10:35