多次使用python操作mysql資料庫,先與大家分享一下,關于如何使用python操作mysql資料庫。mysql并不是python自帶的子產品,是以需要下載下傳安裝。(在windows平台下介紹該使用過程)
1、下載下傳/安裝python-mysql
輕按兩下下載下傳的檔案,一直選擇next就可以安裝好(前提是必須已經安裝了python),注意python-mysql與python對應的版本,否則在使用過程中會出現意想不到的錯誤。
2、檢查是否安裝成功
打開python互動界面,輸入import MySQLdb,沒有報錯表示成功安裝。
如圖:

3、使用方式
測試資料庫為:
3.1 與資料庫建立連接配接# 使用MySQLdb.connect()方法
connection = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="test")
# host : 主機名(IP)
# port : 端口号,mysql預設為3306
# user : 使用者名
# passwd : 密碼
# db : 資料庫(預設連接配接的資料庫)【可選】
# charset : 編碼方式【可選】
# 如果未指定db屬性,那麼可以使用connection.select_db("資料庫名稱")選擇指定資料庫
3.2 擷取遊标對象# 具體的sql執行,都是通過遊标對象完成的;通過連接配接對象的cursor方法擷取遊标對象
# 初始狀态遊标執行第一個元素
cursor = connection.cursor()
3.3 執行SQL語句# 分為單個SQL執行和批量SQL執行,以及是否參數化(可以防止SQL注入)
# query: sql字元串
# args :如果sql字元串為%s占位符那麼args是元組或者清單,如果sql字元串占位符是%(key)s形式## ,那麼是字典類型。否則為None(預設)
# 文法1:cursor.execute(query, args)
# 文法2:cursor.executemany(query, args)
# 範例1:使用文法1查詢資料
import MySQLdb
if __name__ == "__main__":
# create mysql connection
connection = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="test")
# get cursor
cursor = connection.cursor()
# 傳回執行結果數
# nums = cursor.execute("select * from user where id=%s", [1]) # 使用%s占位符
nums = cursor.execute("select * from user where id = %(id)s", {"id" : 1}) # 使用%(key)s占位符
print(nums)
print(cursor.fetchone())
# 範例2:使用文法2查詢一條資料
import MySQLdb
if __name__ == "__main__":
# create mysql connection
connection = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="test")
# get cursor
cursor = connection.cursor()
# 傳回執行結果數;
nums = cursor.executemany("select * from user where id=%s", [[1], [2]])
print(nums)
print(cursor.fetchone())
print(cursor.fetchmany())
print(cursor.fetchall())
# 結果是:nums = 2, 但是查詢結果卻是id=2的結果;那是因為nums表示執行了多少個execute方法,# 而執行查詢結果,卻是覆寫了上一個結果,是以當使用文法2查詢時,執行傳回最後一個條件的結果
對上述兩種文法,這裡做一些闡述:
1、execute:執行單條sql語句,并傳回sql語句執行的結果數量
2、executemany:執行多條sql語句,内部實際是多次調用execute,但是比顯示這樣調用效率要高一些,傳回execute執行成功的數量(實際就是sql語句的sql執行的結果數量。
當執行更新(插入、修改、删除)操作時,需要通過connection.commit()顯示執行送出,才會将execute或者executemany執行的結果,映射到資料庫中。
當執行查詢操作時,需要使用cursor.fetchone()、cursor.fetchmany(size), cursor.fetchall(),擷取一個、多個、全部sql執行查詢的結果。如果使用cursor.frtchmany()預設會擷取一個,如果想擷取指定個數,那麼可以使用cursor.fetchmany(size=2)方式。
3.4 查詢時遊标的了解
3.4.1 遊标規則
如果使用同一個cursor.execute()執行查詢結果,初始狀态遊标執行首個元素,當使用cursor.fetch*時,遊标會向下移動;
cursor.fetchone : 向下移動一個位置
cursor.fetchmany(size=num) : 向下移動size指定數值位置
cursor.fetchall() :遊标移動到末尾
例如:import MySQLdb
if __name__ == "__main__":
# create mysql connection
connection = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="test")
# get cursor
cursor = connection.cursor()
# 傳回執行結果數
nums = cursor.execute("select * from user")
print(cursor.fetchone())
print(cursor.fetchmany(size=1))
print(cursor.fetchall())
執行結果:
(1L, 'admin')
((2L, 'wangzp'),)
((6L, 'wangzp12'), (5L, 'wangzp123'))
根據結果可以發現,遊标會移動,按照上述描述的規則。
3.4.2 設定遊标位置
可以通過cursor.scroll(position, mode="relative | absolute")方法,來設定相對位置遊标和絕對位置遊标。
方法參數描述:
position : 遊标位置
mode : 遊标位置的模式,relative:預設模式,相對目前位置;absolute:絕對位置
例如:
mode=relative, position=1;表示的是設定遊标為目前位置+1的位置,即向下移動一個位置
mode=absolute, position=2;将遊标移動到索引為2的位置
代碼示例:import MySQLdb
if __name__ == "__main__":
# create mysql connection
connection = MySQLdb.connect(host="127.0.0.1", port=3306, user="root", passwd="root", db="test")
# get cursor
cursor = connection.cursor()
# 傳回執行結果數
nums = cursor.execute("select * from user")
print(cursor.fetchone()) # 執行後,遊标移動到索引位置為1
cursor.scroll(1) # 相對遊标移動模式,目前索引+1,即遊标位置為2
print(cursor.fetchmany(size=1)) # 是以擷取第3個元素
cursor.scroll(0, mode="absolute") # 絕對索引模式,将遊标重置為0
print(cursor.fetchall()) # 是以擷取所有資料
運作結果:
(1L, 'admin')
((6L, 'wangzp12'),)
((1L, 'admin'), (2L, 'wangzp'), (6L, 'wangzp12'), (5L, 'wangzp123'))
3.5 事務管理
使用connection.commit()送出,connection.rollback()復原。
總結:
除了上述一些用法外,還有一些注入執行存儲過程等方法,這裡不做介紹,詳情可以參考相關文檔。其實用法相對還是比較簡單的。一般開發可以分為如下步驟:
1、建立資料庫連接配接
2、擷取遊标
3、執行SQL
4、如果sql是查詢,那麼使用fetch系列函數查詢,但是需要注意的是遊标的移動方式。
如下列一個簡單的封裝代碼(部分):import MySQLdb
class DBUtil(object):
@staticmethod
def getConnection(host, port, user, password, db):
"get mysql connection"
connection = None
try:
connection = MySQLdb.connect(host=host, port=port, user=user, passwd=password, db=db)
except MySQLdb.Error, e:
print(e)
return connection
@staticmethod
def getCursor(connection):
"get cursor"
cursor = None
try:
cursor = connection.cursor()
except MySQLdb.Error, e:
print(e)
return cursor
@staticmethod
def update(cursor, sql, args):
return cursor.execute(sql, args)
@staticmethod
def updateAndCommit(connection, cursor, sql, args):
nums = cursor.execute(sql, args)
connection.commit()
return nums
@staticmethod
def updateBatch(cursor, sql, args):
return cursor.executemany(sql, args)
@staticmethod
def updateBatchAndCommit(connection, cursor, sql, args):
nums = cursor.executemany(sql, args)
connection.commit()
return nums
if __name__ == "__main__":
connection = DBUtil.getConnection("127.0.0.1", 3306, "root", "root", "test")
cursor = DBUtil.getCursor(connection)
nums = cursor.execute("select * from user")
print(cursor.fetchall())