f you are not familiar with MySQL stored procedures or want to review it as a refresher, you can follow the MySQL stored procedures tutorial.

We will create two stored procedures for the demonstration in this tutorial. The first stored procedure gets all books with authors information from  books and  authors tables:

 
1
2
3
4
5
6
7
8
9
10
11
12
13
DELIMITER $$
 
USE python_mysql$$
 
CREATE PROCEDURE find_all()
BEGIN
SELECT title, isbn, CONCAT(first_name,' ',last_name) AS author
FROM books
INNER JOIN book_author ON book_author.book_id =  books.id
INNER JOIN AUTHORS ON book_author.author_id = authors.id;
END$$
 
DELIMITER ;

The  find_all() stored procedure has a SELECT statement with JOIN clauses that retrieve title, isbn and author’s full name from  books and  authors tables. When we execute the find_all() stored procedure, it returns a result as follows:

 
1
CALL find_all();

The second stored procedure named  find_by_isbn() that is used to find a book by its ISBN as follows:

 
1
2
3
4
5
6
7
8
9
DELIMITER $$
 
CREATE PROCEDURE find_by_isbn(IN p_isbn VARCHAR(13),OUT p_title VARCHAR(255))
    BEGIN
SELECT title INTO p_title FROM books
WHERE isbn = p_isbn;
    END$$
 
DELIMITER ;

The  find_by_isbn() accepts two parameters: the first parameter is isbn (IN parameter) and second is title (OUT parameter). When you pass the isbn to the stored procedure, you will get the title of the book, for example:

 
1
2
CALL find_by_isbn('1235927658929',@title);
SELECT @title;

Calling stored procedures from Python

To call a stored procedure in Python, you follow the steps below:

  1. Connect to MySQL database by creating a new MySQLConnection object.
  2. Instantiate a new MySQLCursor object from the MySQLConnection object by calling the cursor() method.
  3. Call  callproc() method of the MySQLCursor object. You pass the stored procedure’s name as the first argument of the  callproc() method. If the stored procedure requires parameters, you need to pass a list as the second argument to the  callproc() method. In case the stored procedure returns a result set, you can invoke the  stored_results()method of the MySQLCursor object to get a list iterator and iterate this result set by using the  fetchall() method.
  4. Close the cursor and database connection as always.

The following example demonstrates how to call the  find_all() stored procedure in Python and output the result set.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
 
def call_find_all_sp():
    try:
        db_config = read_db_config()
        conn = MySQLConnection(**db_config)
        cursor = conn.cursor()
 
        cursor.callproc('find_all')
 
        # print out the result
        for result in cursor.stored_results():
            print(result.fetchall())
 
    except Error as e:
        print(e)
 
    finally:
        cursor.close()
        conn.close()
 
if __name__ == '__main__':
    call_find_all_sp()

The following example shows you how to call the  find_by_isbn() stored procedure.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
 
def call_find_by_isbn():
    try:
        db_config = read_db_config()
        conn = MySQLConnection(**db_config)
        cursor = conn.cursor()
 
        args = ['1236400967773', 0]
        result_args = cursor.callproc('find_by_isbn', args)
 
        print(result_args[1])
 
    except Error as e:
        print(e)
 
    finally:
        cursor.close()
        conn.close()
 
if __name__ == '__main__':
    call_find_by_isbn()

The  find_by_isbn() stored procedure requires two parameters therefore we have to pass a list ( args ) that contains two elements: the first one is isbn (1236400967773) and the second is 0. The second element of the args list (0) is just a placeholder to hold the  p_title parameter.

The  callproc() method returns a list ( result_args ) that contains two elements: the second element (result_args[1]) holds the value of the  p_title parameter.

In this tutorial, we have shown you how to call stored procedures in Python by using callproc() method of the MySQLCursor object.

Related Tutorials

Home / Python MySQL Tutorial / Calling MySQL Stored Procedures in Python Calling MySQL Stored Procedures in Python的更多相关文章

  1. python爬虫--爬取某网站电影信息并写入mysql数据库

    书接上文,前文最后提到将爬取的电影信息写入数据库,以方便查看,今天就具体实现. 首先还是上代码: # -*- coding:utf-8 -*- import requests import re im ...

  2. python学习之老男孩python全栈第九期_数据库day005知识点总结 —— MySQL数据库day5

    三. MySQL视图(不常用) 给某个查询语句设置个别名(视图名),日后方便使用 - 创建: create view 视图名 as SQL; PS:视图是虚拟的 - 修改: alter view 视图 ...

  3. mysql下面的INSTALL-BINARY的内容,所有的mysql的配置内容都在这

    2.2 Installing MySQL on Unix/Linux Using Generic Binaries Oracle provides a set of binary distributi ...

  4. CentOS6.7下使用非root用户(普通用户)编译安装与配置mysql数据库并使用shell脚本定时任务方式实现mysql数据库服务随机自动启动

    CentOS6.7下使用非root用户(普通用户)编译安装与配置mysql数据库并使用shell脚本定时任务方式实现mysql数据库服务随机自动启动1.关于mysql?MySQL是一个关系型数据库管理 ...

  5. mysql数据库从删库到跑路之mysql基础

    一 数据库是什么 之前所学,数据要永久保存,比如用户注册的用户信息,都是保存于文件中,而文件只能存在于某一台机器上. 如果我们不考虑从文件中读取数据的效率问题,并且假设我们的程序所有的组件都运行在一台 ...

  6. mysql数据库从删库到跑路之mysql完整性约束

    一 介绍 约束条件与数据类型的宽度一样,都是可选参数 作用:用于保证数据的完整性和一致性主要分为: PRIMARY KEY (PK) 标识该字段为该表的主键,可以唯一的标识记录 FOREIGN KEY ...

  7. mysql数据库从删库到跑路之mysql其他

    一 IDE工具介绍 生产环境还是推荐使用mysql命令行,但为了方便测试,可以使用IDE工具 下载链接:https://pan.baidu.com/s/1bpo5mqj 掌握: #1. 测试+链接数据 ...

  8. MySQL高级学习笔记(一):mysql简介、mysq linux版的安装(mysql 5.5)

    文章目录 MySQL简介 概述 mysql高手是怎样炼成的 mysq linux版的安装(mysql 5.5) 下载地址 拷贝&解压缩 检查工作 检查当前系统是否安装过mysql 检查/tmp ...

  9. 【夯实Mysql基础】MySQL性能优化的21个最佳实践 和 mysql使用索引

    本文地址 分享提纲: 1.为查询缓存优化你的查询 2. EXPLAIN 你的 SELECT 查询 3. 当只要一行数据时使用 LIMIT 1 4. 为搜索字段建索引 5. 在Join表的时候使用相当类 ...

  10. Mac mySql ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock' (2)的解决办法

    我的环境:Mac 10.11.6 ,mysql  5.7.14  . mac mySql 报错ERROR 2002 (HY000): Can't connect to local MySQL serv ...

随机推荐

  1. 使用 WPF+ ASP.NET MVC 开发 在线客服系统 (一)

    近段时间利用业余时间开发了一套在线客服系统,期间遇到过大大小小不少问题,好在都一一解决,最终效果也还可以,打算写一个系列的文章把开发过程详细的记录下来. 希望能够和更多的开发人员互相交流学习,也希望有 ...

  2. [ASP.NET MVC 小牛之路]01 - 理解MVC模式

    本人博客已转移至:http://www.exblr.com/liam  PS:MVC出来很久了,工作上一直没机会用.出于兴趣,工作之余我将展开对MVC的深入学习,通过博文来记录所学所得,并希望能得到各 ...

  3. Bower是什么?

    一.简介 Bower是一个客户端技术的软件包管理器,它可用于搜索.安装和卸载如JavaScript.HTML.CSS之类的网络资源.其它一些建立在Bower基础之上的开发工具,如YeoMan和Grun ...

  4. 每天一个linux命令(47):iostat命令

    Linux系统​中的 iostat是I/O statistics(输入/输出统计)的缩写,iostat工具将对系统的磁盘操作活动进行监视.它的特点是汇报磁盘活动统计情况,同时也会汇报出CPU使用情况. ...

  5. C#设计模式系列:桥接模式(Bridge)

    1.桥接模式简介 1.1>.定义 当一个抽象可能有多个实现时,通常用继承来进行协调.抽象类定义对该抽象的接口,而具体的子类则用不同的方式加以实现.继承机制将抽象部分与它的实现部分固定在一起,使得 ...

  6. KVC & KVO

    KVC和KVO看上去又是两个挺牛的单词简写,KVC是Key-Value Coding的简写,是键值编码的意思.KVO是Key-Value  Observing的简写,是键值观察的意思.那么我们能拿KV ...

  7. Openfire/XMPP学习之——Openfire的安装、配置

    一.Openfire下载: 官方下载:http://www.igniterealtime.org/downloads/index.jsp 在官方下载站点,可以获取Windows.Linux.Mac三种 ...

  8. 最大连续子序列乘积(DP)

    题目来源:小米手机2013年校园招聘笔试题 题目描述: 给定一个浮点数序列(可能有正数.0和负数),求出一个最大的连续子序列乘积. 输入: 输入可能包含多个测试样例.每个测试样例的第一行仅包含正整数 ...

  9. es6分享——变量的解构赋值

    变量的解构赋值:ES6 允许按照一定模式,从数组和对象中提取值,对变量进行赋值,这被称为解构(Destructuring). 以前的写法: var a = 1; var b = 2; es6允许的写法 ...

  10. 用Spire.doc来合并邮件

      用Spire.doc来合并邮件 让我们想象一下这样的场景:你在一家IT公司上班.某天公司的某一产品大幅度升级了.然后你需要通知所有的客户.这真是很长的名单.一个个的通知他们是有点蠢的,因为这要花费 ...