zoukankan      html  css  js  c++  java
  • Python--day46--mysql存储过程(不常用)(包含防sql注入)

    一、存储过程:

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

    二、创建存储过程:

    1、简单

    创建存储过程:

    Python中使用结果集:

     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()

    运行结果:

    3、参数 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)是有值的。

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

    例1:

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

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

    三、总结:

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

  • 相关阅读:
    luogu P1144 最短路计数
    luogu P1440 求m区间内的最小值
    cogs 1075. [省常中2011S4] 最短路径问题
    luogu P2485 [SDOI2011]计算器
    luogu P1220 关路灯
    笨小猴 2008年NOIP全国联赛提高组
    [CF580E]Kefa and Watch
    [HDU2138]How many prime numbers
    [NOIp2014提高组]解方程
    [洛谷1390]公约数的和
  • 原文地址:https://www.cnblogs.com/xudj/p/10388360.html
Copyright © 2011-2022 走看看