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

pymysql executemany 也是蛮耿直的

  •  
  •   wuwukai007 · 2022-08-23 11:41:28 +08:00 · 2052 次点击
    这是一个创建于 583 天前的主题,其中的信息可能已经有所发展或是发生改变。
    book 表  id,name,price
    con = pymysq.connect()
    db = con.cursor()
    data = db.execute("select name,price from origin_book").fetchall()
    '''
    data= [('x1',100),('x2',200)]
    '''
    db.execute("insert into book(name,price) values(%s,%s)",data)
    
    
    • 数组里面是元组,executemany 批量插入报错占位符
    • 把 data 改成 [ ['x1', 100] , ['x2', 200] ] 数组套数组就好了,太耿直了
    4 条回复    2022-08-24 11:04:19 +08:00
    chendl111
        1
    chendl111  
       2022-08-23 12:01:38 +08:00 via Android
    这是语法问题吧?
    kkeep
        2
    kkeep  
       2022-08-23 13:09:15 +08:00 via Android
    你 fetchall 出来的('x1',100) 可能并不是 tuple 是 RowProxy 之类的吧 ,只是打印出来是这个样子,
    abersheeran
        3
    abersheeran  
       2022-08-23 19:04:11 +08:00
    你 fetch 出来的是类 Mapping 的 Row 对象……
    xooass
        4
    xooass  
       2022-08-24 11:04:19 +08:00
    conn = pymysql.connect(
    host="127.0.0.1",
    user="",password="",
    database="",
    charset="",
    cursorclass=pymysql.cursors.DictCursor
    )

    cursor = conn.cursor()
    cursor.execute("SQL")
    data = cursor.fetchall()

    ref = data['orders']

    不用 tuple ,用 dict 精准命中
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1034 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:20 · PVG 03:20 · LAX 12:20 · JFK 15:20
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.