Python--day46--mysql存储过程(不经常使用)(包含防sql注入)

1、存储过程:

优势:只要传不多的数据到数据库就能够了   缺点:dba管理数据库的时候可能会对数据库进行了更改了那一坨sql语句。python

2、建立存储过程:

一、简单

建立存储过程:mysql

Python中使用结果集:sql

 1 #
 2 import pymysql  3 
 4 #
 5 conn = pymysql.connect(host="localhost",user='root',password='123456',database="db5",charset='utf8')  6 #游标
 7 cursor = conn.cursor()  8 #链接数据库成功
 9  10 #执行存储过程 11 cursor.callproc('p1') 12 conn.commit() 13 
14 
15 #获取结果集
16 result = cursor.fetchall() 17 print(result) 18 
19 
20 #关闭数据库
21 cursor.close() 22 conn.close()

2,传参数:(in,out,inout三个关键字)

建立存储过程:数据库

直接在mysql数据库中调用并传参:

python中调用并传参:

 1 import pymysql  2 
 3 #
 4 conn = pymysql.connect(host="localhost",user='root',password='123456',database="db5",charset='utf8')  5 #游标
 6 cursor = conn.cursor()  7 #链接数据库成功
 8 
 9 #执行存储过程
10 cursor.callproc('p2',(12,2)) 11 conn.commit() 12 
13 
14 #获取结果集
15 result = cursor.fetchall() 16 print(result) 17 
18 
19 #关闭数据库
20 cursor.close() 21 conn.close()

运行结果:fetch

三、参数 out

python中的参数out:

 1 import pymysql  2 
 3 #
 4 conn = pymysql.connect(host="localhost",user='root',password='123456',database="db5",charset='utf8')  5 #游标
 6 cursor = conn.cursor()  7 #链接数据库成功
 8 
 9 #执行存储过程
10 cursor.callproc('p3',(12,2)) 11 #获取结果集
12 r1 = cursor.fetchall() 13 print(r1) 14 
15 
16 #拿存储过程out回来的结果集 17 #@_p3_0表示查询p3的第个参数,@_p3_1表示第二个参数 18 cursor.execute('select @_p3_0,@_p3_1') 19 #获取结果集 20 r2 = cursor.fetchall() 21 print(r2)
22 23 24 #关闭数据库 25 cursor.close() 26 conn.close()

4,参数inout:inout即能往里面传值也能往外面传值

好比 out n2 int;set @v1=10;给n2传了一个值10,假设有print的时候(没有print),当print (n2)的时候是没有值的,而intout n2 int的时候print (n2)是有值的。spa

5,事务(其中一个出错就回滚到原来的状态)

例1:

6,游标(不经常使用,银行中的数据要进行分门别类进行计算的时候才要用到游标,能不用游标就不用游标)

7,动态执行sql(防sql注入)

3、总结:

为何有结果集又有out伪造的返回值?

相关文章
相关标签/搜索