Home / Python MySQL Tutorial / Calling MySQL Stored Procedures in Python Calling MySQL Stored Procedures in Python

来源:http://www.cnblogs.com/kungfupanda/archive/2016/10/08/5937326.html
-Advertisement-
Play Games

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 ...


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

Python MySQL Stored Procedure Example

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


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 一、綜述 SuperIO(SIO)定位在PC終端(上位機)應用,它只有一個服務實例,配置參數是全局屬性。但是,ServerSuperIO(SSIO)與SuperIO(SIO)定位不一樣,SSIO定位在伺服器端,不管是串口通訊模式,還是網路通訊模式,都支持多服務實例,所以每個服務實例都有自己的配置參數 ...
  • 今天寫了一個英漢詞典小程式,我加了好多註釋,適合初學者一起參考,哪裡寫的不好請幫忙指出,一起學習進步。。 這裡用到了,泛型,泛型字典,一些控制項的操作,split的應用,數組的應用,時間間隔,linkLabel的使用。。 using System; using System.Collections.G ...
  • 註明:相關資料參考來自網路 PHP中使用fopen()函數打開文件,函數語法fopen(filename,mode,include_path,context),filename為要打開的文件,mode為訪問類型,include_path和context為可選。 mode說明 r 只讀方式打開,在文件 ...
  • 【轉自】http://blog.csdn.net/foamflower/article/details/5713604 isNotEmpty將空格也作為參數,isNotBlank則排除空格參數 StringUtils方法的操作對象是java.lang.String類型的對象,是JDK提供的Strin ...
  • 在網路編程中,出於節約帶寬或者編碼的需要,通常需要以原生方式處理long和int,而不是轉換為string。 public class ByteOrderUtils { public static byte[] int2byte(int res) { byte[] targets = new byt ...
  • 什麼是Optional對象 Java 8中所謂的Optional對象,即一個容器對象,該對象可以包含一個null或非null值。如果該值不為null,則調用isPresent()方法將返回true,且調用get()方法會返回該值。 另外,該對象還有其它方法: 如可以使用orElse()方法給Opti ...
  • 裝飾器實際上就是函數,可以在裝飾器中置入通用功能的代碼來降低程式的複雜度。 功能: >引入日誌 >增加計時邏輯來檢測性能 >給函數加入事務的能力 例子1、簡單裝飾器 例子2、含返回值的裝飾器 例子3、複雜裝飾器 這裡是含參數的裝飾器,在裝飾器中調用before方法和after方法,完成對List方法 ...
  • RabbitMQ簡介 AMQP,即Advanced Message Queuing Protocol,高級消息隊列協議,是應用層協議的一個開放標準,為面向消息的中間件設計。消息中間件主要用於組件之間的解耦,消息的發送者無需知道消息使用者的存在,反之亦然。AMQP的主要特征是面向消息、隊列、路由(包括 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...