您好,登錄后才能下訂單哦!
如何通過twisted實(shí)現(xiàn)數(shù)據(jù)庫異步插入?
1. 導(dǎo)入adbapi
2. 生成數(shù)據(jù)庫連接池
3. 執(zhí)行數(shù)據(jù)數(shù)據(jù)庫插入操作
4. 打印錯(cuò)誤信息,并排錯(cuò)
#!/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): # 對數(shù)據(jù)庫進(jìn)行插入操作,并不需要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): # 打印錯(cuò)誤 if failure: print(failure) if __name__ == '__main__': # 數(shù)據(jù)庫基本配置 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)' # 普通方法插入數(shù)據(jù) # conn = pymysql.connect(**db_settings) # cursor = conn.cursor() # cursor.execute(insert_sql, '1') # conn.commit() try: # 生成連接池 db_conn = adbapi.ConnectionPool('pymysql', **db_settings) # 通過連接池執(zhí)行具體的sql操作,返回一個(gè)對象 query = db_conn.runInteraction(go_insert, insert_sql) # 對錯(cuò)誤信息進(jìn)行提示處理 query.addCallbacks(handle_error) except Exception as e: print(e) # 定時(shí),給4秒時(shí)間讓twisted異步框架完成數(shù)據(jù)庫插入異步操作,沒有定時(shí)什么都不會做 reactor.callLater(4, reactor.stop) reactor.run()
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。