python mysql模組

來源:互聯網
上載者:User

標籤:python mysql 模組

    多次使用python操作mysql資料庫,先與大家分享一下,關於如何使用python操作mysql資料庫。mysql並不是python內建的模組,因此需要下載安裝。(在windows平台下介紹該使用過程)

    1、下載/安裝python-mysql

    :https://pypi.python.org/pypi/MySQL-python/1.2.5

    雙擊下載的檔案,一直選擇next就可以安裝好(前提是必須已經安裝了python),注意python-mysql與python對應的版本,否則在使用過程中會出現意想不到的錯誤。

    

    2、檢查是否安裝成功

    開啟python互動介面,輸入import MySQLdb,沒有報錯表示成功安裝。

    

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M01/4B/E7/wKiom1Q1BwmhuQFQAAD8KhjDYt0669.jpg" title="first.png" alt="wKiom1Q1BwmhuQFQAAD8KhjDYt0669.jpg" />

    3、使用方式

    測試資料庫為:

650) this.width=650;" src="http://s3.51cto.com/wyfs02/M00/4B/F2/wKioL1Q1_PySvM4aAABndSJAeiA507.jpg" title="user.png" alt="wKioL1Q1_PySvM4aAABndSJAeiA507.jpg" />

    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 MySQLdbif __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 MySQLdbif __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 MySQLdbif __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 MySQLdbif __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 MySQLdbclass 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())


本文出自 “java程式冥” 部落格,請務必保留此出處http://793404905.blog.51cto.com/6179428/1561650

python mysql模組

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.