python資料庫操作 - PyMySQL入門

來源:互聯網
上載者:User
PyMySQL是Python中操作MySQL的模組,和之前使用的MySQLdb模組準系統一致,PyMySQL的效能和MySQLdb幾乎相當,如果對效能要求

不是特別的強,使用PyMySQL將更加方便,PyMySQL是完全使用python編寫,避免了MySQLdb跨系統分別安裝的麻煩。

適用環境

python版本 >=2.6或3.3

mysql版本>=4.1


安裝

在命令列下執行命令:

pip install pymysql

手動安裝,請先下載。下載地址:https://github.com/PyMySQL/PyMySQL/tarball/pymysql-X.X。


其中的X.X是版本。


下載後解壓壓縮包。在命令列中進入解壓後的目錄,執行如下的指令:

python setup.py install

建議使用pip安裝, 可以自動解決包依賴問題,避免安裝中出現各種錯誤。


pymysql的基本操作如下:

#!/usr/bin/env python#   --coding = utf-8#   Author Allen Leeimport pymysql#建立連結化物件conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123', db='Allen')#建立遊標cursor = conn.cursor()#執行sql,更新單條資料,並返回受影響行數effect_row = cursor.execute("update hosts set host = '1.1.1.2'")#插入多條,並返回受影響的函數effect_row = cursor.executemany("insert into hosts(host,color_id)values(%s,%s)",[("1.0.0.1",1,),("10.0.0.3",2)])#擷取最新自增IDnew_id = cursor.lastrowid#查詢資料cursor.execute("select * from hosts")#擷取一行row_1 = cursor.fetchone()#擷取多(3)行row_2 = cursor.fetchmany(3)#擷取所有row_3 = cursor.fetchall()#重設遊標類型為字典類型cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)#提交,儲存建立或修改的資料conn.commit()#關閉遊標cursor.close()#關閉串連conn.close()
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.