1. 程式人生 > >python中MySQLdb的使用

python中MySQLdb的使用

lba delete 查看 ctc align 亂碼 import llb 主機名

<1>linux版本

http://sourceforge.net/projects/mysql-python/ 下載,在安裝是要先安裝setuptools,然後在下載文件目錄下,修改mysite.cfg,指定本地mysql的mysql-config文件的路徑

<2>windows版本

網上搜索到一個http://www.technicalbard.com/files/MySQL-python-1.2.2.win32-py2.6.exe

安裝後import MySQLdb會出現 DeprecationWarning: the sets module is deprecated 這樣一個警告,google之

原因是2.6不知sets這個模塊,不過已經添加了set內置函數。找到MySQLdb文件夾的中__init__.py,註釋掉from sets import ImmutableSet class DBAPISet(ImmutableSet):添加class DBAPISet(frozenset):;找到converters.py註釋掉from sets import BaseSet, Set。然後修改第45行和129行中的Set為set。

搞定。

PS:我是在http://www.lfd.uci.edu/~gohlke/pythonlibs/下載的MySQL-python-1.2***版本

下面開始操作的demo:

Python代碼

 1     # -*- coding: utf-8 -*-       
 2     #mysqldb      
 3     import time, MySQLdb      
 4          
 5     #連接      
 6     conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")    
 7     cursor = conn.cursor()      
 8       
 9     #刪除表  
10 sql = "drop table if exists user" 11 cursor.execute(sql) 12 13 #創建 14 sql = "create table if not exists user(name varchar(128) primary key, created int(10))" 15 cursor.execute(sql) 16 17 #寫入 18 sql = "insert into user(name,created) values(%s,%s)" 19 param = ("aaa",int(time.time())) 20 n = cursor.execute(sql,param) 21 print insert,n 22 23 #寫入多行 24 sql = "insert into user(name,created) values(%s,%s)" 25 param = (("bbb",int(time.time())), ("ccc",33), ("ddd",44) ) 26 n = cursor.executemany(sql,param) 27 print insertmany,n 28 29 #更新 30 sql = "update user set name=%s where name=‘aaa‘" 31 param = ("zzz") 32 n = cursor.execute(sql,param) 33 print update,n 34 35 #查詢 36 n = cursor.execute("select * from user") 37 for row in cursor.fetchall(): 38 print row 39 for r in row: 40 print r 41 42 #刪除 43 sql = "delete from user where name=%s" 44 param =("bbb") 45 n = cursor.execute(sql,param) 46 print delete,n 47 48 #查詢 49 n = cursor.execute("select * from user") 50 print cursor.fetchall() 51 52 cursor.close() 53 54 #提交 55 conn.commit() 56 #關閉 57 conn.close()

輸出結果:

insert 1
insertmany 3
update 1
(u‘bbb‘, 1340790602L)
bbb
1340790602
(u‘ccc‘, 33L)
ccc
33
(u‘ddd‘, 44L)
ddd
44
(u‘zzz‘, 1340790602L)
zzz
1340790602
delete 1
((u‘ccc‘, 33L), (u‘ddd‘, 44L), (u‘zzz‘, 1340790602L))

基本的使用如上,還是很簡單的,進一步使用還沒操作,先從網上找點資料放上來,以備後續查看

1.引入MySQLdb庫

import MySQLdb

2.和數據庫建立連接
conn=MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable",charset="utf8")
提供的connect方法用來和數據庫建立連接,接收數個參數,返回連接對象.

比較常用的參數包括
host:數據庫主機名.默認是用本地主機.
user:數據庫登陸名.默認是當前用戶.
passwd:數據庫登陸的秘密.默認為空.
db:要使用的數據庫名.沒有默認值.
port:MySQL服務使用的TCP端口.默認是3306.
charset:數據庫編碼.

更多關於參數的信息可以查這裏
http://mysql-python.sourceforge.net/MySQLdb.html

然後,這個連接對象也提供了對事務操作的支持,標準的方法
commit() 提交
rollback() 回滾

3.執行sql語句和接收返回值
cursor=conn.cursor()
n=cursor.execute(sql,param)
首先,我們用使用連接對象獲得一個cursor對象,接下來,我們會使用cursor提供的方法來進行工作.這些方法包括兩大類:1.執行命令,2.接收返回值

cursor用來執行命令的方法:
callproc(self, procname, args):用來執行存儲過程,接收的參數為存儲過程名和參數列表,返回值為受影響的行數
execute(self, query, args):執行單條sql語句,接收的參數為sql語句本身和使用的參數列表,返回值為受影響的行數
executemany(self, query, args):執行單條sql語句,但是重復執行參數列表裏的參數,返回值為受影響的行數
nextset(self):移動到下一個結果集

cursor用來接收返回值的方法:
fetchall(self):接收全部的返回結果行.
fetchmany(self, size=None):接收size條返回結果行.如果size的值大於返回的結果行的數量,則會返回cursor.arraysize條數據.
fetchone(self):返回一條結果行.
scroll(self, value, mode=‘relative‘):移動指針到某一行.如果mode=‘relative‘,則表示從當前所在行移動value條,如果mode=‘absolute‘,則表示從結果集的第一行移動value條.

下面的代碼是一個完整的例子.
#使用sql語句,這裏要接收的參數都用%s占位符.要註意的是,無論你要插入的數據是什麽類型,占位符永遠都要用%s
sql="insert into cdinfo values(%s,%s,%s,%s,%s)"
#param應該為tuple或者list
param=(title,singer,imgurl,url,alpha)
#執行,如果成功,n的值為1
n=cursor.execute(sql,param)

#再來執行一個查詢的操作
cursor.execute("select * from cdinfo")
#我們使用了fetchall這個方法.這樣,cds裏保存的將會是查詢返回的全部結果.每條結果都是一個tuple類型的數據,這些tuple組成了一個tuple
cds=cursor.fetchall()
#因為是tuple,所以可以這樣使用結果集
print cds[0][3]
#或者直接顯示出來,看看結果集的真實樣子
print cds

MySQLdb呢,其實和Python內置的sqlite3的使用方法基本相同。MySQLdb默認情況下,查詢結果行都是返回tuple,訪問的時候不是很方便,必須按照0,1這樣讀取。

結果就像這樣:

(u‘ccc‘, 33L)
(u‘ddd‘, 44L)
(u‘zzz‘, 1340790602L)

以前使用sqllite3的時候,可以修改過Connection對象的row_factory屬性,以便使用sqlite3.Row,這樣結果集中的數據行就是字典形式的,可以用字段名訪問,那麽MySQLdb中是不是也有這樣的方法呢,經過在網上搜索發現,MySQLdb中有DictCursor,要做到這點也很簡單,那就是建立數據庫連接是傳遞cusorclass參數,或者在獲取Cursor對象時傳遞cusorclass參數即可:
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8",cursorclass=MySQLdb.cursors.DictCursor)
cursor = conn.cursor()
或者
conn=MySQLdb.connect(host="localhost",user="root",passwd="root",db="test",charset="utf8")
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)

返回結果就是這樣:

{‘name‘: u‘ccc‘, ‘created‘: 33L}
{‘name‘: u‘ddd‘, ‘created‘: 44L}
{‘name‘: u‘zzz‘, ‘created‘: 1340790602L}


#如果需要批量的插入數據,就這樣做
sql="insert into cdinfo values(0,%s,%s,%s,%s,%s)"
#每個值的集合為一個tuple,整個參數集組成一個tuple,或者list
param=((title,singer,imgurl,url,alpha),(title2,singer2,imgurl2,url2,alpha2))
#使用executemany方法來批量的插入數據.這真是一個很酷的方法!
n=cursor.executemany(sql,param)

4.關閉數據庫連接
需要分別的關閉指針對象和連接對象.他們有名字相同的方法
cursor.close()
conn.close()

四步完成,基本的數據庫操作就是這樣了.下面是兩個有用的連接
MySQLdb用戶指南: http://mysql-python.sourceforge.net/MySQLdb.html
MySQLdb文檔: http://mysql-python.sourceforge.net/MySQLdb-1.2.2/public/MySQLdb-module.html

5 編碼(防止亂碼)

需要註意的點:

1 Python文件設置編碼 utf-8 (文件前面加上 #encoding=utf-8)
2 MySQL數據庫charset=utf-8
3 Python連接MySQL是加上參數 charset=utf8
4 設置Python的默認編碼為 utf-8 (sys.setdefaultencoding(utf-8)

1     #encoding=utf-8   
2     import sys   
3     import MySQLdb   
4         
5     reload(sys)   
6     sys.setdefaultencoding(utf-8)   
7         
8     db=MySQLdb.connect(user=root,charset=utf8)   

註:MySQL的配置文件設置也必須配置成utf8

設置 MySQL 的 my.cnf 文件,在 [client]/[mysqld]部分都設置默認的字符集(通常在/etc/mysql/my.cnf):

[client]
default-character-set = utf8
[mysqld]
default-character-set = utf8

python中MySQLdb的使用