Python开发【笔记】:pymsyql 插入一条数据同时…

2018-06-18 02:50:37来源:未知 阅读 ()

新老客户大回馈,云服务器低至5折

一、通过cursor.lastrowid

import pymysql.cursors

# Connect to the database

connection = pymysql.connect(host='192.168.90.10',
                             port=3306,
                             user='remote',
                             password='123456',
                             db='Jefrey',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor,
                             autocommit = True)

try:

    with connection.cursor() as cursor:  # 增加
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
        print(cursor.lastrowid)
finally:
    connection.close()

# 87

 

二、通过sql语句SELECT LAST_INSERT_ID()

import pymysql.cursors

# Connect to the database

connection = pymysql.connect(host='192.168.90.10',
                             port=3306,
                             user='remote',
                             password='123456',
                             db='Jefrey',
                             charset='utf8mb4',
                             cursorclass=pymysql.cursors.DictCursor,
                             autocommit = True)

try:

    with connection.cursor() as cursor:  # 增加
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
        sql = 'SELECT LAST_INSERT_ID() AS id;'
        cursor.execute(sql)
        database = cursor.fetchone()
        print(database)
finally:
    connection.close()

# {'id': 88}

 

表结构:

 

标签:

版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com
特别注意:本站所有转载文章言论不代表本站观点,本站所提供的摄影照片,插画,设计作品,如需使用,请与原作者联系,版权归原作者所有

上一篇:python-1基础总结

下一篇:最新整理知识结构图