如何通過twisted實現數據庫異步插入?
1. 導入adbapi
2. 生成數據庫連接池
3. 執行數據數據庫插入操作
4. 打印錯誤信息,並排錯
#!/usr/bin/python3
__author__ = 'beimenchuixue'
__blog__ = 'http://www.cnblogs.com/2bjiujiu/'
import pymysql
from twisted.enterprise import adbapi
from twisted.internet import reactor
def go_insert(cursor, sql):
# 對數據庫進行插入操作,並不需要commit,twisted會自動幫我commit
try:
for i in range(10):
data = str(i)
cursor.execute(sql, data)
except Exception as e:
print(e)
def handle_error(failure):
# 打印錯誤
if failure:
print(failure)
if __name__ == '__main__':
# 數據庫基本配置
db_settings = {
'host': 'localhost',
'db': 'jobole',
'user': 'root',
'password': 'passwort',
'charset': 'utf8',
'use_unicode': True
}
# sql語句模版
insert_sql = 'insert into test_1(text_1) value(%s)'
# 普通方法插入數據
# conn = pymysql.connect(**db_settings)
# cursor = conn.cursor()
# cursor.execute(insert_sql, '1')
# conn.commit()
try:
# 生成連接池
db_conn = adbapi.ConnectionPool('pymysql', **db_settings)
# 通過連接池執行具體的sql操作,返回一個對象
query = db_conn.runInteraction(go_insert, insert_sql)
# 對錯誤信息進行提示處理
query.addCallbacks(handle_error)
except Exception as e:
print(e)
# 定時,給4秒時間讓twisted異步框架完成數據庫插入異步操作,沒有定時什么都不會做
reactor.callLater(4, reactor.stop)
reactor.run()
