设为首页 加入收藏

TOP

使用python操作mysql
2017-10-10 21:05:48 】 浏览:7714
Tags:使用 python 操作 mysql
  版权申明:本文为博主窗户(Colin Cai)原创,欢迎转帖。如要转贴,必须注明原文网址

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

  作者:窗户

  QQ:6679072

  E-mail:6679072@qq.com

 

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

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

-- 数据库名称为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
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()用于遍历下一个结果集,此用于多结果集的存储过程。

  最终关闭打开的数据库。

  运行一下

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

  

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇工资系统--练习文件的操作(增改查) 下一篇Python 逐行分割大txt文件

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目