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
Cola90
V2EX  ›  Python

Python 下操作 MySQL 批量插入的一个问题?

  •  
  •   Cola90 · 2016-04-07 15:59:38 +08:00 · 4686 次点击
    这是一个创建于 2934 天前的主题,其中的信息可能已经有所发展或是发生改变。

    表里面有主键为‘ 1234 ’,‘ 3456 ’的两个数据,现在用 Python 批量插入几条新数据 cursor.executemany(Insert into test ( id ) value(%s),('1234'),('6789'),(‘ 9876 ’)) 由于主键 1234 已经存在,这条代码回出错,同时 6789 、 9876 也会插入失败,有办法直接跳过 1234 这条数据,然后进行批量插入吗?

    9 条回复    2016-04-07 23:50:44 +08:00
    lxy
        1
    lxy  
       2016-04-07 16:11:33 +08:00
    insert ignore into ?
    swjtutipo
        2
    swjtutipo  
       2016-04-07 16:17:17 +08:00   ❤️ 1
    insert into xxxxx on duplicate key set xxx
    Cola90
        3
    Cola90  
    OP
       2016-04-07 16:17:18 +08:00
    @lxy 并不行,只是没了错误提示
    Cola90
        4
    Cola90  
    OP
       2016-04-07 16:18:18 +08:00
    @swjtutipo 是一个办法,但是我希望不要加入重复数据
    fish267
        5
    fish267  
       2016-04-07 16:19:21 +08:00
    delete if exists
    qile1
        6
    qile1  
       2016-04-07 20:20:59 +08:00 via Android
    先判断是否有主健,有就更新数据,没有就插入
    Neveroldmilk
        7
    Neveroldmilk  
       2016-04-07 21:35:42 +08:00
    检索是否存在,如果存在要么更新,要么删除重新插入。
    billgreen1
        8
    billgreen1  
       2016-04-07 22:44:01 +08:00
    insert into table on duplicate update
    lunaticus7
        9
    lunaticus7  
       2016-04-07 23:50:44 +08:00
    用 replace
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   880 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 21:57 · PVG 05:57 · LAX 14:57 · JFK 17:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.