码迷,mamicode.com
首页 > 数据库 > 详细

Mysql学习---使用Python执行存储过程

时间:2018-07-29 15:18:38      阅读:254      评论:0      收藏:0      [点我收藏+]

标签:too   use   width   imp   select   charset   dict   ctc   href   

使用Python执行存储过程

使用Python执行存储过程[2部分]:

1.执行存储过程,获取存储过程的结果集
  2.将返回值设置给了  @_存储过程名_序号 =

#!/usr/bin/env python
# -*- coding:utf-8 -*-
import pymysql
conn = pymysql.connect(host=‘127.0.0.1‘, port=3306, user=‘root‘, passwd=‘‘, db=‘test_python‘, charset=‘utf8‘)
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 执行存储过程
# @_p3_0 = 1, 相当于Python帮我们创建了变量,所以返回值也是放在了这个变量里面,需要我们手动获取
# @_p3_1 = 2
# @_p3_2 = 3
# @_p3_3 = 0
ret1 = cursor.callproc(‘p3‘, args=(1, 2, 3, 0))
# print(‘ret1:‘, ret1)   # 传递参数过去 ret1: (1, 2, 3, 0),同时执行了存储过程将结果放在内存
result = cursor.fetchall()  # 从内存获取返回值,[{‘@_p3_0‘: 1, ‘@_p3_3‘: 7, ‘@_p3_1‘: 2, ‘@_p3_2‘: 103}]
print(‘返回的参数:‘, result, ‘\n‘)

# 获取执行完存储的参数,因为Python帮我们将结果放在了变量里,所以需要从变量里面获取
ret2 = cursor.execute("select @_p3_0,@_p3_1,@_p3_2,@_p3_3")
# print(‘ret2:‘, ret2)       # 什么都不执行: ret2: 1
result2 = cursor.fetchall()      # 获取返回值,[{‘@_p3_0‘: 1, ‘@_p3_3‘: 7, ‘@_p3_1‘: 2, ‘@_p3_2‘: 103}]
print(‘返回的结果集:‘, result2)

conn.commit()   # 因为存储过程里面有多个sql语句,可能有selete,insert等语句,所以为了保证代码的完整
cursor.close()
conn.close()

技术分享图片

技术分享图片

Mysql学习---使用Python执行存储过程

标签:too   use   width   imp   select   charset   dict   ctc   href   

原文地址:https://www.cnblogs.com/ftl1012/p/9385253.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!