V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
llonglongago
V2EX  ›  Python

大佬们,请教一个 Python 下关于 duckdb 的数据导入很诡异的问题,困扰了我两天,不胜感激。

  •  
  •   llonglongago · 6 天前 · 656 次点击
    大佬们,请教一个 Python 下关于 duckdb 的数据导入很诡异的问题,困扰了我两天,不胜感激。

    背景:
    最近在搞一个小爬虫,用到了 duckdb 需要在导入的时候进行去重更新,因为导入的时候跨越数据时间久远无法在代码中就实现去重,只能通过 duckdb 的数据库机制去重

    表结构如下
    CREATE TABLE IF NOT EXISTS ticai (
    "一级类目" TEXT,
    "一级类目" TEXT,
    "人数" BIGINT,
    UNIQUE("一级类目", "一级类目"))

    data_df 为一个 frame
    columns 为列名
    placeholders 为占位符个数

    代码:
    #拼接导入语句 INSERT OR REPLACE INTO 将现有行的每一列更新为要插入的行的新值
    sql_str = f'"""INSERT OR REPLACE INTO ticai ({columns}) VALUES ({placeholders})"""'
    #duckdb 执行批量导入
    con.executemany(sql_str, data_df.values.tolist())

    症状:
    使用拼接语句执行 con.executemany ()就一直报错,结果如下
    duckdb.duckdb.ParserException: Parser Error: syntax error at or near """"INSERT OR REPLACE INTO ticai (""

    但是使用打印出来的 sql_str 拼接语句就能执行成功
    con.executemany("""INSERT OR REPLACE INTO ticai ("一级类目", "二级类目", "人数") VALUES (?, ?, ?)""", data_df.values.tolist())

    结果如下:<duckdb.duckdb.DuckDBPyConnection object at 0x000001586624C2F0>

    超级诡异,我不是很精通 Python ,也木有在其他平台找到问题的症结,球球大佬们帮忙解答下
    2 条回复    2024-09-11 11:57:57 +08:00
    customsshen
        1
    customsshen  
       6 天前
    单引号和双引号不能包含三引号
    llonglongago
        2
    llonglongago  
    OP
       6 天前
    @customsshen
    好使,感谢,确实是我基础不牢了。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2399 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 22ms · UTC 14:58 · PVG 22:58 · LAX 07:58 · JFK 10:58
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.