Python知识分享网 - 专业的Python学习网站 学Python,上Python222
pymysql调用存储过程
发布于:2023-09-19 10:48:10

1小时学会 Python操作Mysql数据库之pymysql模块技术https://www.bilibili.com/video/BV1Dz4y1j7Jr

 

 

我们首先创建一个简单的存储过程

 

DELIMITER //

CREATE PROCEDURE test_add(m INT,n INT, OUT result INT)
BEGIN
SET result=m+n;

END; //

 

测试:

 

SET @s=0;
CALL test_add(1,2,@s);
SELECT @s

 

pymysql调用存储过程  图1

 

Pymysql调用存储过程实现:

 

from pymysql import Connection

con = None

try:
    # 创建数据库连接
    con = Connection(
        host="localhost",  # 主机名
        port=3306,  # 端口
        user="root",  # 账户
        password="123456",  # 密码
        database="db_python",  # 指定操作的数据库
        autocommit=True  # 设置自动提交
    )
    # 获取游标对象
    cursor = con.cursor()
    # 使用游标对象,调用存储过程
    cursor.execute("CALL test_add(1,2,@s);")
    cursor.execute("select @s;")
    result = cursor.fetchone()
    print(result[0])
    # 确认提交
    # con.commit()
except Exception as e:
    print("异常:", e)
finally:
    if con:
        # 关闭连接
        con.close()

 

 

 

转载自: