当autocommit为开启状态时,即使没有手动start transaction开启事务,mysql默认也会将用户的操作当做事务即时提交(自动帮我们 db.commit())

autocommit开启时,mysql的插入效率会提高

1.autocmmit=False

import pymysql
import time


def mysql_autpcommit():
    strat_time = time.time()
    db = pymysql.connect(host='localhost', port=3306, database='cfda', user='root', password='root', charset='utf8',
                         autocommit=False)
    cursor = db.cursor()

    title = '14省份大到暴雨来袭! 双台风或相互影响'
    for i in range(1000):
        cursor.execute('insert into async_test_async(title) values("{}")'.format(title))
        db.commit()
        print("\r I:{}".format(i), end='')

    print('耗时:{}'.format(time.time() - strat_time))


if __name__ == "__main__":
    mysql_autpcommit()

# 结果:  耗时:3.388371467590332  autocommit=False

2.autocmmit=Ture

import pymysql
import time


def mysql_autpcommit():
    strat_time = time.time()
    db = pymysql.connect(host='localhost', port=3306, database='cfda', user='root', password='root', charset='utf8',
                         autocommit=True)
    cursor = db.cursor()

    title = '14省份大到暴雨来袭! 双台风或相互影响'
    for i in range(1000):
        cursor.execute('insert into async_test_async(title) values("{}")'.format(title))
        # db.commit()
        print("\r I:{}".format(i), end='')

    print('耗时:{}'.format(time.time() - strat_time))


if __name__ == "__main__":
    mysql_autpcommit()

# 结果:  耗时:2.4238381385803223 autocommit=True