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

pymysql 操作 直接插入数据库 有什么办法 得到该记录的 id 并赋值给 tp_id ?

  •  
  •   python30 · 2019-10-13 23:38:09 +08:00 · 2851 次点击
    这是一个创建于 1627 天前的主题,其中的信息可能已经有所发展或是发生改变。
    pymysql 操作 直接插入数据库

    xxx.py 文件里

    sql = 'INSERT INTO xxx (`a_id`, `title`, `body`) VALUES (%s, %s, %s)'

    value = (tttt, tttt, tttt,)

    conn.execute(sql, value)

    这一句如果想得到 面上面插入数据的 ID

    用下面三句

    tp_id =conn.execute('select LAST_INSERT_ID();')
    tp_id = conn.execute('select max(id) from xxx;')
    tp_id = conn.execute('select @@identity')

    上面三个语句 都是返回 执行成功的行数 也就是说 tp_id 的结果是 1 或者 0

    那有什么办法 得到该记录的 id 并赋值给 tp_id ?
    用 conn.lastrowid 可以。
    但是不知道用 上面三条语句中的方法怎么得出这个 ID 并赋值给 tp_id ?

    谢谢
    7 条回复    2019-10-15 15:28:20 +08:00
    rogwan
        1
    rogwan  
       2019-10-14 00:19:32 +08:00 via iPhone
    自增 ID 不好处理,如果是非自增 ID,插入记录之前记录下来就好了。
    renmu
        2
    renmu  
       2019-10-14 00:27:37 +08:00 via Android
    conn.insert_id() 这个试试
    liuguichao
        3
    liuguichao  
       2019-10-14 09:23:19 +08:00
    result_proxy = self.execute(sql, args)
    id = result_proxy.lastrowid
    meowoo
        4
    meowoo  
       2019-10-14 10:59:22 +08:00
    直接用 cursor.lastrowid 就行了
    meowoo
        5
    meowoo  
       2019-10-14 11:01:02 +08:00
    你后面写的那三个,不都是对数据库做查询么,直接解析查询结果就好了啊
    python30
        6
    python30  
    OP
       2019-10-14 13:25:31 +08:00
    @meowoo
    现在就是直接用的 tp_id = cursor.lastrowid

    第一个 insert into xxxx 后

    第二个 现在可以用: 'INSERT INTO aaa (`a_id`, `body`) VALUES (LAST_INSERT_ID(), 'bbbbbb')'

    但是我后面还想再跟 一个 'INSERT INTO bbb (`b_id`, `body`) 这个 b_id 也是用的第一个 insert into xxxx 后的记录 id

    但是第三个再用 LAST_INSERT_ID() 的话,得到的就是第二个 插入表的 记录 id 了

    说的有点混乱。
    实在不行就暂时先用 tp_id = cursor.lastrowid 这个吧
    meowoo
        7
    meowoo  
       2019-10-15 15:28:20 +08:00
    @python30 我觉得你这样过于复杂了吧, 非得这样的话,就需要先查出来,定义一个变量保存呗
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4131 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 10:16 · PVG 18:16 · LAX 03:16 · JFK 06:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.