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

SQLite报OperationalError: near ")": syntax error错误求助

问题:pandas导出数据到SQLite时触发OperationalError: near ")": syntax error

用户代码

# export data to sqlite
with sqlite3.connect('realtime_crypto.sqlite') as conn:
    df.to_sql('data', con=conn, if_exists='append', index=False)

报错信息

OperationalError                          Traceback (most recent call last)
Input In [5], in <cell line: 218>()
    232 # export data to sqlite
    233 with sqlite3.connect('realtime_crypto.sqlite') as conn:
--> 234     df.to_sql('data', con=conn, if_exists='append', index=False)

OperationalError: near ")": syntax error

解决方法

  • 排查DataFrame列名:这个错误大概率是列名出问题——要么有空列名,要么列名用了SQL保留字(比如order、group)、特殊字符(空格、括号等)。先执行print(df.columns)列出所有列名检查。
  • 重命名非法列名:找到问题列名后直接修改,比如把空列名改成unknown_col,带空格的列名改成下划线分隔的格式:
    df.rename(columns={" ": "price_usd", "": "unknown_col"}, inplace=True)
    
  • 手动指定列数据类型:自动推断类型偶尔会出问题,用dtype参数明确指定每个列的SQL类型(需先安装sqlalchemy):
    from sqlalchemy import types
    
    dtype_map = {
        "crypto_name": types.VARCHAR(255),
        "price": types.FLOAT,
        "timestamp": types.DATETIME
    }
    df.to_sql('data', con=conn, if_exists='append', index=False, dtype=dtype_map)
    
  • 确认DataFrame非空:如果DataFrame没有任何行或列,生成的建表语句会有语法错误,先通过df.shape确认数据非空。
  • 重置表结构:如果之前手动修改过SQLite表结构,导致和DataFrame不匹配,直接删表重建:
    with sqlite3.connect('realtime_crypto.sqlite') as conn:
        conn.execute("DROP TABLE IF EXISTS data")
        df.to_sql('data', con=conn, if_exists='append', index=False)
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 18:05:38