python中mysql的相关操作

安装第三方模块:MYSQLdb:

下载地址:https://pypi.python.org/pypi/MySQL-python/1.2.4

 安装会自动检测python的安装环境的,不需要任何配置

一、相应DML命令

import os, sys, string
import MySQLdb

#连接数据库
try:
    conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='feng',db='test')
except Exception, e:
    print e
    sys.exit()
# 获取cursor对象来进行操作
cursor = conn.cursor()

#插入单条数据
sql = "insert into staffinfo(i_staff_no,v_staff_name) values (%d, '%s')"%(333,"ccc")
try:
    cursor.execute(sql)
except Exception, e:
    print e
#插入多条数据
sql = "insert into staffinfo(i_staff_no,v_staff_name) values (%s, %s)"#此处都是%s类型
val = ((444,"ddd"),(555,"eee"), (666,"fff"))
try:
    cursor.executemany(sql, val)
except Exception, e:
    print e

#查询数据
sql= "select * from staffinfo order by i_staff_no"
cursor.execute(sql)
alldata = cursor.fetchall()
# 如果有数据返回,就循环输出, alldata是有个二维的列表
if alldata:
    for rec in alldata:
        print rec[0], rec[1]

cursor.close()
conn.close()

运行结果:


 二、调用存储过程

  1、带参数的存储过程

     存储过程:

DELIMITER //  
create procedure python_pro_param(in _i_staff_no int,out _v_staff_name varchar(50))
begin
    select v_staff_name into _v_staff_name
    from staffinfo
    where i_staff_no=_i_staff_no;
end
//
DELIMITER  ;

调用:

import os, sys, string
import MySQLdb

i_staff_no=222
v_staff_name=''

try:
    conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='feng',db='test')
except Exception, e:
    print e
    sys.exit()
       
cursor=conn.cursor()   
cursor.callproc('python_pro_param',(i_staff_no,v_staff_name))   
cursor.execute('select @_python_pro_param_0,@_python_pro_param_1')#0:第一个参数
data=cursor.fetchall()                                            #1:第二个参数
if data:
    for rec in data:     
        v_staff_name=rec[1]   
        print i_staff_no,v_staff_name

cursor.close()
conn.close()

运行结果:

    

  2、返回结果集的存储过程

     存储过程:

DELIMITER //  
create procedure python_pro_dataset(in _i_staff_no_start int,in _i_staff_no_end int)
begin
    select i_staff_no,v_staff_name
    from staffinfo
    where i_staff_no between _i_staff_no_start and _i_staff_no_end;
end
//
DELIMITER  ;

调用:

import os, sys, string
import MySQLdb

i_staff_no_start=222
i_staff_no_end=555

try:
    conn = MySQLdb.connect(host='127.0.0.1',user='root',passwd='feng',db='test')
except Exception, e:
    print e
    sys.exit()

cursor=conn.cursor()        
cursor.execute('call python_pro_dataset(%s,%s)',(i_staff_no_start,i_staff_no_end))   
data=cursor.fetchall()   
if data:
    for rec in data:   
        print rec[0],rec[1]
        cursor.nextset()

cursor.close()
conn.close()

运行结果:

   


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值