1. 程式人生 > >Python pymysql模塊學習心得

Python pymysql模塊學習心得

auto 使用 create 文檔 one mysql模塊 中斷 import tps

PyMySQL包含了一個純Python的MySQL客戶端的庫,它的目的是用來替換MySQLdb,並且工作在CPython,PyPy和IronPython。

PyMySQL官方地址:https://pypi.python.org/pypi/PyMySQL#documentation

下面是一個簡單的例子和說明:

dbInfo={
    host: host_IP,
    port: 3306,
    user: user_name,
    password: password,
     db: db_name,
     charset: utf8,}
def queryMysql(sql):

#將數據庫的信息當成字段傳給connect(),這樣方便數據和函數分離,也可以直接在connect()裏面寫出參數 conn
= pymysql.connect(**dbInfo)
#建立連接後創建遊標 cur
= conn.cursor()
#執行sql語句,select語句還需要fetch才能拿到數據,否則返回的是數據個數 cur.execute(sql) res
=cur.fetchall() cur.close()
#sql語句不是自動提交的,需要手動提交才能保持修改 conn.commit()
#執行sql語句後關閉連接 conn.close()
return res sql=select * from table_name result=queryMysql(sql) print(result)

下面是官方文檔的例子,說明已經很詳細了,我再簡單補充一下:

import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host=localhost,
                             user=user,
                             password=passwd,
                             db
=db, charset=utf8mb4, cursorclass=pymysql.cursors.DictCursor)#cursorclass選擇返回數據的格式,字典或者列表。 #try語句防止出現assert中斷 try: #使用with語句可以免去關閉connection的操作 with connection.cursor() as cursor: # Create a new record sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)" cursor.execute(sql, ([email protected], very-secret)) # connection is not autocommit by default. So you must commit to save # your changes. connection.commit() with connection.cursor() as cursor: # Read a single record sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s" cursor.execute(sql, ([email protected],)) result = cursor.fetchone() print(result) finally: connection.close()

Python pymysql模塊學習心得