python中mysql的相關操作

2021-07-04 20:22:58 字數 3346 閱讀 3678

安裝第三方模組:mysqldb:

安裝會自動檢測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()

執行結果:

mysql中的length函式相關

引用 在mysql中length是計算欄位的長度乙個漢字是算三個字元,乙個數字或字母算乙個字元了,與char length是有一點區別,本文章重點介紹第乙個函式。mysql裡面的length函式是乙個用來獲取字串長度的內建函式。具體用法示例如下 1 檢視某字串的長度 比如本站 select leng...

mysql中tinyint相關的知識

tinyint 1 boolean 寫查詢語句的時候要 字段 1 as name 轉一下,出來的就是1,0,取的時候用biginteger獲取 tinyint 4 3位的int mysql中tinyint smallint int和bigint型別的用法區別 tinyint占用1位元組的儲存空間,即...

python中列表的相關操作

usr bin env python 初始化空列表 方式一 list test 方式二 list test1 list print 方式一建立的空列表 format list test list test print 方式二建的空列表 format list test1 list test1 初始化...