使用python操作mysql

时间:2022-04-27
本文章向大家介绍使用python操作mysql,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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