如何通過(guò)twisted實(shí)現(xiàn)數(shù)據(jù)庫(kù)異步插入?
1. 導(dǎo)入adbapi
2. 生成數(shù)據(jù)庫(kù)連接池
3. 執(zhí)行數(shù)據(jù)數(shù)據(jù)庫(kù)插入操作
4. 打印錯(cuò)誤信息,并排錯(cuò)
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): # 對(duì)數(shù)據(jù)庫(kù)進(jìn)行插入操作,并不需要commit,twisted會(huì)自動(dòng)幫我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ù)庫(kù)基本配置 db_settings = { 'host' : 'localhost' , 'db' : 'jobole' , 'user' : 'root' , 'password' : 'passwort' , 'charset' : 'utf8' , 'use_unicode' : True } # sql語(yǔ)句模版 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) # 通過(guò)連接池執(zhí)行具體的sql操作,返回一個(gè)對(duì)象 query = db_conn.runInteraction(go_insert, insert_sql) # 對(duì)錯(cuò)誤信息進(jìn)行提示處理 query.addCallbacks(handle_error) except Exception as e: print (e) # 定時(shí),給4秒時(shí)間讓twisted異步框架完成數(shù)據(jù)庫(kù)插入異步操作,沒(méi)有定時(shí)什么都不會(huì)做 reactor.callLater( 4 , reactor.stop) reactor.run() |
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.cnblogs.com/2bjiujiu/p/7242292.html