python操做mysql

1、安裝第三方模塊:MYSQLdbpython

  一、地址:http://sourceforge.net/projects/mysql-python/mysql

    新的可用地址:https://pypi.python.org/pypi/MySQL-python/1.2.4sql

 

  

  二、安裝數據庫

    

   安裝前:(site-packages目錄)fetch

   

   安裝後:(site-packages目錄)spa

   

2、執行DML語句.net

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

  運行結果:code

  

 3、調用存儲過程對象

  一、帶參數的存儲過程blog

     存儲過程:

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

    運行結果:

    

  二、返回結果集的存儲過程

     存儲過程:

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

   運行結果:

   

相關文章
相關標籤/搜索