#定義存儲過程,並命名爲proc_traceLog
1 BEGIN 2 #聲明臨時變量 3 DECLARE planNo VARCHAR(32); 4 DECLARE trainNo VARCHAR(32); 5 DECLARE content VARCHAR(255); 6 DECLARE done int DEFAULT 0 ; 7 8 DECLARE cur_train CURSOR FOR 9 SELECT p.plan_no,p.train_no,g.operate_content 10 FROM nature_order_plan p LEFT JOIN 11 (SELECT c.`no`,c.operate_content 12 FROM common_log c JOIN( SELECT `no`,MAX(id) id FROM common_log GROUP BY `no`) l ON c.id = l.id 13 )g ON p.plan_no = g.`no` 14 WHERE p.`status` = 40 15 AND p.transport_way = '鐵運門到站'; 16 17 #設置循環結束標誌 18 DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; 19 20 #若是臨時表已存在,刪除臨時表 21 DROP TABLE IF EXISTS tmpTable; 22 23 #建立臨時表 24 CREATE TABLE tmpTable 25 ( 26 plan_no VARCHAR(32), 27 train_no VARCHAR(32), 28 cabinet_no VARCHAR(32), 29 operate_content VARCHAR(255) 30 ); 31 32 #打開遊標 33 OPEN cur_train; 34 35 #遍歷遊標 36 REPEAT 37 FETCH cur_train INTO planNo,trainNo,content; 38 IF NOT done THEN 39 #有火車號,則將計劃單號、火車號、最新日誌插入到臨時表 40 IF trainNo THEN 41 INSERT INTO tmpTable(plan_no,train_no,operate_content) VALUES(planNo,trainNo,content); 42 #不然插入計劃單號、集裝箱號、對應的最新日誌到臨時表 43 ELSE 44 INSERT INTO tmpTable(plan_no,cabinet_no,operate_content) 45 SELECT p.plan_no,c.cabinet_no,l.operate_content 46 FROM nature_order_plan p JOIN nature_order_plan_cabinet c ON p.plan_no = c.plan_no 47 LEFT JOIN(SELECT a.`no` AS plan_no,b.canbinet_no,a.operate_content 48 FROM common_log a JOIN( SELECT `no` AS plan_no,SUBSTR(operate_content FROM 5 FOR 11) AS canbinet_no,MAX(id) AS id 49 FROM common_log 50 WHERE source = '12306' 51 AND module = 2 52 AND type = 0 53 AND `no` = planNo 54 GROUP BY SUBSTR(operate_content FROM 5 FOR 11) 55 ) b ON a.id = b.id 56 )l ON c.plan_no = l.plan_no AND c.cabinet_no = l.canbinet_no 57 WHERE p.plan_no = planNo; 58 END IF; 59 END IF; 60 UNTIL done 61 END REPEAT; #循環結束 62 CLOSE cur_train; 63 END
注意:MySQL定義遊標以前不能定義別的操做語句,因此把定義表放在了定義遊標的後面python
python3調用存儲過程以下:mysql
import pymysql.cursors class CrawlDao(): def __init__(self): self.connect = pymysql.connect(host=getDBHost(), port=getDBPort(), user=getDBUsername(), passwd=getDBPassword(), db=getDBDatabase(), charset=getDBCharset()) self.cursors = self.connect.cursor() self.logger = Logger('CrawlDao').getLogger() def selectPlanOrderLog(self): ''' 調用存儲過程proc_traceLog,將狀態爲服務中,運輸方式爲鐵運的計劃單插入到tmpTable表中 tmpTable表數據分爲2部分,一部分是火車號train_no不爲空,則不查詢集裝箱號cabinet_no,最新日誌取最新一條 第二部分是火車號train_no爲空,查詢集裝箱號及對應的最新日誌(截取操做日誌取集裝箱號進行關聯) :return:計劃單號、火車號、集裝箱號、最新操做日誌 '''
#調用存儲過程 self.cursors.callproc('proc_traceLog') cmd = 'SELECT plan_no,train_no,cabinet_no,operate_content FROM tmpTable;' try: self.cursors.execute(cmd) result_tuple = self.cursors.fetchall() return result_tuple # 返回數據類型爲元祖 except Exception as e: self.logger("查詢計劃單失敗:%s" % e) finally: self.cursors.close() self.connect.close()