標籤:python常用代碼
Description
MySQLdb is a Python DB API-2.0-compliant interface; see PEP-249 for details. For up-to-date versions of MySQLdb, use the homepage link.
Supported versions:
* MySQL versions from 3.23 to 5.5; 5.0 or newer recommended. MariaDB should also work.
* Python versions 2.4-2.7; Python 3 support coming soon.
ZMySQLDA is a Database Adapter for Zope2.
注意、MySQL資料庫要用MySQLdb模組,但Python用來連結MySQL的第三方庫MySQLdb不支援Python3.x
安裝MySQLdb
下載 MySQL-python-1.2.4b4.tar.gz
[[email protected] IdcCheck]# wget http://downloads.sourceforge.net/project/mysql-python/mysql-python-test/1.2.4b4/MySQL-python-1.2.4b4.tar.gz?r=https%3A%2F%2Fsourceforge.net%2Fprojects%2Fmysql-python%2F&ts=1478767096&use_mirror=jaist .[[email protected] IdcCheck]# tar -zxvf MySQL-python-1.2.4b4.tar.gz
解壓縮
[[email protected] IdcCheck]# tar -zxvf MySQL-python-1.2.4b4.tar.gz
執行[[email protected] IdcCheck]# cd MySQL-python-1.2.4b4
編譯
[[email protected] MySQL-python-1.2.4b4]# python setup.py build
安裝
[[email protected] MySQL-python-1.2.4b4]# python setup.py install
測試是否安裝成功,執行如下代碼不報錯,則代表成功
[[email protected] IdcCheck]# pythonPython 2.6.6 (r266:84292, Sep 12 2011, 14:03:14) [GCC 4.4.5 20110214 (Red Hat 4.4.5-6)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> import MySQLdb>>> >>>
串連MySQL資料庫
import MySQLdb# 開啟資料庫連接db = MySQLdb.connect(host="localhost",user="root",passwd="sa",db="mytable")# 使用cursor()方法擷取操作遊標 cursor = db.cursor()
關閉資料庫連接
需要分別的關閉指標對象和連線物件
cursor.close() conn.close()
編碼(防止亂碼)
需要注意的點:
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)
#encoding=utf-8import sysimport MySQLdbreload(sys)sys.setdefaultencoding(‘utf-8‘)db=MySQLdb.connect(user=‘root‘,charset=‘utf8‘)
註:
執行資料庫操作
con=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
#如果需要批量的插入資料,就這樣做
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)
需要注意的是(或者說是我感到奇怪的是),在執行完插入或刪除或修改操作後,需要調用一下conn.commit()方法進行提交.這樣,資料才會真正儲存在資料庫中.我不清楚是否是我的mysql設定問題,總之,今天我在一開始使用的時候,如果不用commit,那資料就不會保留在資料庫中,但是,資料確實在資料庫呆過.因為自動編號進行了累積,而且返回的受影響的行數並不為0.
模組功能示範
#!/usr/bin/pythonimport MySQLdbCon= MySQLdb.connect(host=‘localhost‘,user=‘root‘,passwd=‘root‘,db=‘abc‘)cursor =con.cursor()sql ="select * from myt"cursor.execute(sql)row=cursor.fetchone()print rowcursor.close()con.close()
執行以下SQL語句擷取傳回值:
//擷取串連的遊標cursor=conn.cursor()//查詢sql = "select * from 【table】"//新增sql = "insert into 【table】(欄位,欄位) values(值,值)"//修改sql = "update 【table】 set 欄位 =‘值’where 條件 "//刪除sql = "delete from 【table】where 條件"cursor.execute(sql)
傳回值
cur.execute(‘select * from tables‘)
其傳回值為SQL語句得到的行數,如:2L,表示2行。
然後,可以從該對象的fetchone或fetchall方法得到行資訊。
擷取行資訊
指標對象的fetchone()方法,是每次得到一行的tuple傳回值:
引用
>>> row=cur.fetchone()>>> print row(‘user1‘, ‘52c69e3a57331081823331c4e69d3f2e‘, 1000L, 1000L, ‘/home/FTP/user1‘,‘‘)
指標對象的fetchall()方法,可取出指標結果集中的所有行,返回的結果集一個元組(tuples):
引用
>>> cur.scroll(0,‘absolute‘)>>> row=cur.fetchall()>>> print row((‘user1‘, ‘52c69e3a57331081823331c4e69d3f2e‘, 1000L, 1000L, ‘/home/FTP/user1‘,‘‘), (‘user2‘, ‘7e58d63b60197ceb55a1c487989a3720‘, 1000L, 1000L,‘/home/FTP/user2‘, None))
移動指標
當使用fetchone()方法是,指標是會發生移動的。所以,若不重設指標,那麼使用fetchall的資訊將只會包含指標後面的行內容。
手動移動指標使用:
cur.scroll(int,parm)
含義為:
引用
int:移動的行數,整數;在相對模式下,正數向下移動,負值表示向上移動。
parm:移動的模式,預設是relative,相對模式;可接受absoulte,絕對模式。
修改資料
修改資料,包括插入、更新、刪除。它們都是使用指標對象的execute()方法執行:
cur.execute("insert into table (row1, row2) values (‘111‘, ‘222‘)")cur.execute("update table set row1 = ‘test‘ where row2 = ‘row2‘ ")cur.execute("delete from table where row1 = ‘row1‘ ")
因單引號“‘”用於SQL語句中的標識,所以,python中的字串需使用雙引號括住。
此外,也可以使用python的“格式化字串”寫法,簡化命令,例如:
cur.execute("update table set row1 = ‘%s‘ where row2 = ‘%s‘ "%(‘value1‘,‘value2‘))
※請注意,‘%s‘的單引號是SQL語句的間隔符,‘value1‘的單引號是python的字串間隔符,其含義是不同的。是否需要間隔符,以及使用雙引號還是單引號作為間隔,需根據其含義決定。例如,還有:
cur.execute("update FTPUSERS set passwd=%s where userid=‘%s‘ "%("md5(‘123‘)",‘user2‘))
這裡,paswd=%s是因SQL的md5()函數是不需要單引號間隔的;"md5(‘123‘)"是python的字串中含有單引號,所以用雙引號括住。
提交修改
一般情況下,MySQLdb模組會自動認可修改。但我們在更新資料後,手動運行一次:
conn.commit()
關閉資料庫連接
需要分別的關閉指標對象和連線物件.他們有名字相同的方法
cursor.close()conn.close()
python操作MySQL