在Python中执行存储过程通常涉及以下步骤:
1. 连接到数据库。
3. 使用游标的`callproc`方法执行存储过程,传递必要的参数。
4. 获取存储过程返回的结果集。
5. 处理结果集并输出或进一步操作。
6. 关闭游标和数据库连接。
import pymysql
连接数据库
conn = pymysql.connect(host='127.0.0.1', user='root', password='root', database='fruitdb', charset='utf8')
创建游标对象
cur = conn.cursor()
调用存储过程,假设存储过程名为'searchAllFruit'
cur.callproc('searchAllFruit')
提交事务
conn.commit()
获取存储过程返回的结果集
result = cur.fetchall()
打印结果
for row in result:
name = row
price = row
count = row
total = row
print('{} {} {} {}'.format(name, price, count, total))
关闭游标和数据库连接
cur.close()
conn.close()
请注意,存储过程名在调用时通常需要用引号括起来,参数以元组的形式传递给`callproc`方法。
如果你使用的是其他数据库(如MS SQL Server),连接和调用存储过程的方式可能会有所不同,但基本步骤类似。