UNIQUE 约束 pymsql 插入数据

# -*- coding: utf-8 -*-
import pymysql


def insert_db(items_list):
    db = pymysql.connect(host='localhost',
                         database='shops1',
                         user='shops1',
                         port=3306,
                         password='123456')
    cursor = db.cursor()
    insert_sql = "INSERT IGNORE INTO tp_shops(sellerId,shopName) VALUES (%s,%s)"
    try:
        result = cursor.executemany(insert_sql, items_list)
        db.commit()
        return result
    except Exception as e:
        print(e)
        # 如果发生错误则回滚
        db.rollback()
    # 关闭数据库连接
    db.close()


if __name__ == '__main__':
    shop = [565656565, '磬格旗舰店']
    shops = [(894111711, 'aaaaaaaaaa'),(895746871, '6568878787887'),(565656565656666666666, '6568878787887')]
    print(insert_db(shops))

 

类似文章