在python中加速提交MySQL数据库

2024-05-18 07:54:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一些代码,可以根据行ID是否已经存在,在MySQL数据库中添加或更新行。为了做到这一点,我有一个循环,循环遍历所有ID,并分别提交每个ID

但是它非常慢。更新200000行大约需要20分钟。我需要它快得多。有人知道如何一次将多行提交到DB吗

以下是我目前的代码:

app = Flask(__name__)
app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql://username:password@localhost/dbName'
db = SQLAlchemy(app)

class Example(db.Model):
        __tablename__ = 'sessionAttendances'
        _id = db.Column('_id', db.Unicode, primary_key=True)
        wondeID = db.Column('wondeID', db.Unicode)
        date = db.Column('date', db.Unicode)
        timezoneType = db.Column('timezoneType', db.Unicode)
        timezone = db.Column('timezone', db.Unicode)
        createdAt = db.Column('createdAt', db.Date)
        session = db.Column('session', db.Unicode)
        updatedAt = db.Column('updatedAt', db.Date)

        def __init__(self, _id, wondeID, date, timezoneType, timezone, createdAt, session, updatedAt):
            self._id = _id
            self.wondeID = wondeID
            self.date = date
            self.timezoneType = timezoneType
            self.timezone = timezone
            self.createdAt = createdAt
            self.session = session
            self.updatedAt = updatedAt

        @classmethod
        def add_or_update(cls, _id, wondeID, date, timezoneType, timezone, createdAt, session, updatedAt):
            entity = cls.query.filter_by(_id=row._id).first()

            if not entity:
                entity = cls(row._id, row.wondeID, row.date, row.timezoneType, row.timezone, row.createdAt, row.session, row.updatedAt)
                db.session.add(entity)
                db.session.commit()
                print("Adding Record")
            else:
                entity.wondeID = row.wondeID
                db.session.commit()
                print("Updating Record")

            return entity

for idx,row in sessionAttendance.iterrows():
    example = Example(row._id, row.wondeID, row.date, row.timezoneType, 
                      row.timezone, row.createdAt, row.session, row.updatedAt)
    example.add_or_update(row._id, row.wondeID, row.date, row.timezoneType, 
                          row.timezone, row.createdAt, row.session, row.updatedAt)

Tags: selfiddbdatesessionunicodecolumnrow
3条回答

您需要使用插入。。。在重复密钥更新时。如果该行是新的,则插入该行,否则将更新该行

当使用这种方法时,您应该分批插入(例如:一次插入1000行),mysql将对所有200.000行执行单独的查询

检查本教程:https://www.mysqltutorial.org/mysql-insert-or-update-on-duplicate-key-update/

也许只需尝试使用psycopg2数据库适配器从@Vadim Sirbu用Python运行sql命令

由于您的“id”是您的密码,您可能需要使用session.merge()

https://docs.sqlalchemy.org/en/13/orm/session_state_management.html#merging

SQLAlchemy中的此函数将自动创建或更新现有项

我也强烈建议你不要在每一项之后都承诺。 这可能是代码中最大的延迟。 如果您的循环两次没有包含相同的“id”,我建议您在循环完成后提交

相关问题 更多 >