• 【2022.07.04】executemany的插入前检查值是否存在


    发包给数据库

    def send_to_db(sql,data):
        conn = pymysql.connect(host='',
                               user='',
                               password='',
                               port=,
                               database='',
                               autocommit=True
                               )
        cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
        affect_rows = cursor.executemany(sql, data)
        print('插入行数', affect_rows)
        cursor.close()
        conn.close()
    

    在插入前检查是否已经存在相同数据(不含主键

    def sql_generate(datebase_name, data_list):
        insert_sql = 'INSERT INTO `' + datebase_name + '`('
        count = 0
        all = len(data_list[0].keys())
        for j in data_list[0].keys():
            insert_sql = insert_sql + j
            count = count + 1
            if count<all:
                insert_sql = insert_sql + ','
        insert_sql = insert_sql + ') select '
        count = 0
        for j in data_list[0].keys():
            insert_sql = insert_sql + '%(' + j + ')s'
            count = count + 1
            if count < all:
                insert_sql = insert_sql + ','
        insert_sql = insert_sql + '\nFROM DUAL WHERE NOT EXISTS(SELECT * FROM ' + datebase_name +' WHERE '
        count = 0
        for j in data_list[0].keys():
            insert_sql = insert_sql + j +' = %(' + j + ')s'
            count = count + 1
            if count<all:
                insert_sql = insert_sql + ' and '
        insert_sql = insert_sql + ');'
        print(insert_sql)
        send_to_db(insert_sql, data_list)
        return insert_sql
    

    普通的插入数据

    def sql_generate(datebase_name, data_list):
        insert_sql = 'INSERT INTO `' + datebase_name + '`('
        count = 0
        all = len(data_list[0].keys())
        for j in data_list[0].keys():
            insert_sql = insert_sql + j
            count = count + 1
            if count<all:
                insert_sql = insert_sql + ','
        insert_sql = insert_sql + ') values('
        count = 0
        for j in data_list[0].keys():
            insert_sql = insert_sql + '%(' + j + ')s'
            count = count + 1
            if count < all:
                insert_sql = insert_sql + ','
        insert_sql = insert_sql + ');'
        send_to_db(insert_sql, data_list)
        return insert_sql
    
  • 相关阅读:
    osharp3引入事务后操作结果类别的调整
    Code First 迁移
    表达式拼接Expression<Func<IEntityMapper, bool>> predicate
    ASP.NET中Session的sessionState 4种mode模式
    EF Code First Migrations数据库迁移
    啊里大鱼短信发送API
    asp.net服务器控件的生命周期
    osharp3使用经验:整合DbContextScope 文章 1
    关于MarshalByRefObject的解释
    数据库操作事务IsolationLevel 枚举
  • 原文地址:https://www.cnblogs.com/mokou/p/16442998.html
Copyright © 2020-2023  润新知