SQLAlchemy ON DUPLICATE KEY UPDATE

前端 未结 9 1587
死守一世寂寞
死守一世寂寞 2020-11-27 15:53

Is there an elegant way to do an INSERT ... ON DUPLICATE KEY UPDATE in SQLAlchemy? I mean something with a syntax similar to inserter.insert().execute(lis

9条回答
  •  情歌与酒
    2020-11-27 16:45

    It's depends upon you. If you want to replace then pass OR REPLACE in prefixes

      def bulk_insert(self,objects,table):
        #table: Your table class and objects are list of dictionary [{col1:val1, col2:vale}] 
        for counter,row in enumerate(objects):
            inserter = table.__table__.insert(prefixes=['OR IGNORE'], values=row)
            try:
                self.db.execute(inserter)
            except Exception as E:
                print E
            if counter % 100 == 0:
                self.db.commit()                    
        self.db.commit()
    

    Here commit interval can be changed to speed up or speed down

提交回复
热议问题