如何通過twisted實現(xiàn)數(shù)據(jù)庫異步插入?
1. 導入adbapi
2. 生成數(shù)據(jù)庫連接池
3. 執(zhí)行數(shù)據(jù)數(shù)據(jù)庫插入操作
4. 打印錯誤信息,并排錯
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
|
#!/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ù)庫進行插入操作,并不需要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__' : # 數(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操作,返回一個對象 query = db_conn.runInteraction(go_insert, insert_sql) # 對錯誤信息進行提示處理 query.addCallbacks(handle_error) except Exception as e: print (e) # 定時,給4秒時間讓twisted異步框架完成數(shù)據(jù)庫插入異步操作,沒有定時什么都不會做 reactor.callLater( 4 , reactor.stop) reactor.run() |
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/2bjiujiu/p/7242292.html