python 天气预报 mysql_使用python操作mysql

版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖。如要转贴,必须注明原文网址

http://www.cnblogs.com/Colin-Cai/p/7643047.html

作者:窗户

QQ:6679072

E-mail:6679072@qq.com

python可以使用MYSQLdb来操作数据库。

我们先来建数据库,其SQL语句如下:

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

-- 一个插入的存储过程myinsert

-- 一个返回两个结果集的存储过程myproc

delimiter //

create procedure myinsert(in a_in int, in b_in int)

begin

insert into t(a,b) values(a_in, b_in);

end

//

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

importMySQLdb

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

printsqltry:

cursor.execute(sql)

seq= 1

while 1:if seq > 1:

cursor.nextset()

results=cursor.fetchall()ifresults:print "No.%d" %(seq)

seq= seq + 1

for row inresults:print "%s %s" % (row[0],row[1])else:break

except:print "Wrong"

print "OK"db.close()

以上代码对于有无结果集,有多个结果集(存储过程)的SQL语句都是可以使用的。如果没有结果集,当然不需要cursor,自然也查不出结果集。

cursor.nextset()用于遍历下一个结果集,此用于多结果集的存储过程。

最终关闭打开的数据库。

运行一下

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值