1 2 3 4 5 6 7 8 9 | 版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖。如要转贴,必须注明原文网址 http://www.cnblogs.com/Colin-Cai/p/7643047.html 作者:窗户 QQ:6679072 E-mail:6679072@qq.com |
python可以使用MYSQLdb来操作数据库。
我们先来建数据库,其SQL语句如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | -- http://www.cnblogs.com/Colin-Cai -- 数据库名称为test create database test; use test; -- 生成表t create table t ( a int , b int ); -- 插入数据 start transaction ; insert into t(a,b) values (1,1000); insert into t(a,b) values (1,2000); insert into t(a,b) values (1,3000); insert into t(a,b) values (2,1000); insert into t(a,b) values (2,2000); insert into t(a,b) values (2,3000); insert into t(a,b) values (3,1000); insert into t(a,b) values (3,2000); insert into t(a,b) values (3,3000); commit work ;<br><br> -- 一个插入的存储过程myinsert<br>-- 一个返回两个结果集的存储过程myproc delimiter //<br> create procedure myinsert( in a_in int , in b_in int )<br> begin <br> insert into t(a,b) values (a_in, b_in);<br> end <br>// create procedure myproc( in a_max int , in b_max int ) begin select a,b from t where a <= a_max; select a,b from t where b <= b_max; end // delimiter ; |
python操作数据库代码如下:
#!/usr/bin/python import MySQLdb db = MySQLdb.Connect(host='localhost', user='root', passwd='123456', db='test') cursor = db.cursor() sql = 'call myproc(4,2000)' #sql = 'select a,b from t' #sql = 'insert into t(a,b) values(100,10000)'; print sql try: cursor.execute(sql) seq = 1 while 1: if seq > 1: cursor.nextset() results = cursor.fetchall() if results: print "No.%d" % (seq) seq = seq + 1 for row in results: print "%s %s" % (row[0],row[1]) else: break except: print "Wrong" print "OK" db.close()
以上代码对于有无结果集,有多个结果集(存储过程)的SQL语句都是可以使用的。如果没有结果集,当然不需要cursor,自然也查不出结果集。
cursor.nextset()用于遍历下一个结果集,此用于多结果集的存储过程。
最终关闭打开的数据库。
运行一下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | $ ./test_mysql.py call myproc(4,2000) No .1 1 1000 1 2000 1 3000 2 1000 2 2000 2 3000 3 1000 3 2000 3 3000 No .2 1 1000 1 2000 2 1000 2 2000 3 1000 3 2000 OK |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具