1小時學會 Python操作Mysql數(shù)據(jù)庫之pymysql模塊技術(shù):https://www.bilibili.com/video/BV1Dz4y1j7Jr
我們首先創(chuàng)建一個簡單的存儲過程
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調(diào)用存儲過程實現(xiàn):
from pymysql import Connection
con = None
try:
# 創(chuàng)建數(shù)據(jù)庫連接
con = Connection(
host="localhost", # 主機名
port=3306, # 端口
user="root", # 賬戶
password="123456", # 密碼
database="db_python", # 指定操作的數(shù)據(jù)庫
autocommit=True # 設(shè)置自動提交
)
# 獲取游標對象
cursor = con.cursor()
# 使用游標對象,調(diào)用存儲過程
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:
# 關(guān)閉連接
con.close()