Python 操作mysql存储过程
一.Python操作存储过程
1 #__author: Lobin 2 #__date: 2018/1/30 3 import pymysql 4 conn=pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='root',db='student',charset='utf8') 5 cursor=conn.cursor(cursor=pymysql.cursors.DictCursor) 6 cursor.callproc('p1',args=(1,2,3,4)) 7 r=cursor.fetchall() 8 print(r) 9 r=cursor.execute('select @_p1_0,@_p1_1,@_p1_2,@_p1_3') 10 r=cursor.fetchall() 11 print(r) 12 cursor.close() 13 conn.close() 14 15 #[{'id': 1, 'name': '耿艳春', 'gender': '男'}, {'id': 2, 'name': '耿艳春2', 'gender': '男2'}, {'id': 3, 'name': '黄少波', 'gender': '男'}, {'id': 4, 'name': '王腾飞', 'gender': '男'}] 16 #[{'@_p1_0': 1, '@_p1_1': 2, '@_p1_2': 100, '@_p1_3': 14}]
解析:
1.callpro调用存储过程,参数1'p1'为存储过程名称,参数2为存储过程参数
2.第一次调用后使用fetchall获得结果集
3.使用'select @_p1_0,@_p1_1,@_p1_2,@_p1_3'为固定格式,@_存储过程名_0依次对应参数
4.第二次使用fetchall获得所有参数的值
二、mysql存储过程
1 -- 创建存储过程 2 delimiter \\ 3 create procedure p1( 4 in i1 int, 5 in i2 int, 6 inout i3 int, 7 out r1 int 8 ) 9 BEGIN 10 DECLARE temp1 int; 11 DECLARE temp2 int default 0; 12 13 set temp1 = 1; 14 15 set r1 = i1 + i2 + temp1 + temp2; 16 17 set i3 = i3 + 100; 18 19 end\\ 20 delimiter ;
delimiter为去除;在mysql中执行的作用 在第一个delimiter后面和end后面加同一个 符号 ,最后delimiter加;
in 为传入参数,out为传出参数,inout为传入传出参数
使用declare声明变量,set赋值
1 -- 执行存储过程 2 set @t1 =4; 3 set @t2 = 0; 4 CALL p1 (1, 2 ,@t1, @t2); 5 SELECT @t1,@t2;
上图为执行存储过程的语句
使用call调用 ,select输出结果
浙公网安备 33010602011771号