[Python3]PyMySQL庫

來源:互聯網
上載者:User

標籤:utf-8   提交   建立   python3   實現   code   發送   charset   退出   

概述

本文主要講解如何使用pymysql庫進行MySQL的管理操作。

主要講解如何使用pymysql實現增刪改查動作,並附上對應的樣本。

安裝pymysql
pip install PyMySQL
常用對象及API

在pymysql中提供了Connection和Cursor對象來管理操作MySQL。

常用對象
  • Connection

代表一個與MySQL Server的socket串連,使用connect方法來建立一個串連執行個體。

  • Cursor

代表一個與MySQL資料庫互動對象,使用Connection.Cursor()在當前socket串連上的互動對象。

常用API

Connection對象常用的API:

connect()   建立一個資料庫連接執行個體  begin()     開始一個事務  close()     發送一個退出訊息,並關閉串連  commit()    提交修改至資料庫  cursor()    建立一個cursor(遊標)執行個體  ping()      檢測伺服器是否在運行  rollback()  復原當前事務  select_db(db)   設定當前db  show_warnings() 顯示警告資訊

Cursor對象常用API:

close()     關閉當前cursorexecute()   執行一個sql語句executemany()   執行批量sql語句fetchall()      取所有資料fetchone()      取一條資料
一個基本樣本

下面我們看一個基本的樣本,讓大家感受下pymysql庫的能力。

基本前提,假設你在本地已經安裝了MySQL服務或是你擁有遠端存取某個MySQL服務的許可權。

用下列sql建立一個資料表,以便下面的樣本示範:

# -*- coding:utf-8 -*-import pymysqlimport random__author__ = ‘穀白‘if __name__ == "__main__":        print("PyMySQL基本樣本")        # 建立一個串連執行個體    conn = pymysql.connect(        host="10.68.3.88", # mysql服務ip地址,若服務在本機則用localhost        port=3306,  # mysql服務連接埠        user="liyiming",  # 訪問mysql的使用者名稱        password="liyiming",  # 訪問mysql的密碼        db="zzb_pro",  # 預設串連到的資料庫        charset="utf8"  # 串連字元集    )    try:                # 建立用於互動的cursor對象        cursor = conn.cursor()                                # 先插入10條測試資料        # 構建插入資料的sql        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"        # 產生10條測試資料        sql_data = []                for index in range(0, 10):            email = "%[email protected]" % random.random()            password = random.random()            sql_data.append((email, password))                        # 執行sql,進行批量插入資料        cursor.executemany(sql, sql_data)                        # 提交至資料庫        conn.commit()                        # 查詢5條資料        sql = "SELECT * FROM `users` LIMIT 5"        # 執行sql        cursor.execute(sql)                        # 取查詢到的所有資料        all_data = cursor.fetchall()                # 遍曆列印出來        print("取所有查詢到的資料")                for data in all_data:                        print("id: %d email: %s password: %s" %                 (data[0], data[1], data[2]))                            # 取1條資料        # cursor.execute(sql)        one_data = cursor.fetchone()                print("\n取1條資料")                print("id: %d email: %s password: %s" %             (one_data[0], one_data[1], one_data[2]))    finally:                # 最後把資料庫連接關閉        conn.close()

 

小結
  • 對SQL要熟悉,才能更好的應用PyMySQL庫

  • 其次要注意在構造sql時,最好構建成參數化方式,見樣本

  • 多練習最重要

[Python3]PyMySQL庫

聯繫我們

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