Python資料庫支援:PyMySQL安裝+資料庫連線操作+捕獲異常回滾操作
阿新 • • 發佈:2018-12-17
PyMySQL是python3.x版本中用於連線MySQL伺服器的一個庫,Python2使用的是mysqldb
PyMySQL遵循Python資料庫API v2.0規範,幷包含了pure-Python MySQL客戶端庫。
PyMySQL安裝
地址https://github.com/PyMySQL/PyMySQL
使用pip命令安裝:pip inistall PyMySQL
使用git命令安裝:
git clone https://github.com/PyMySQL/PyMySQL
cd PyMySQL/
Python3 steup.py insttall
資料庫連線操作
匯入模組:import pymysql
開啟資料庫連線
Db = pymysql.connect(host=”localhost”,user=”root”,password=””,db=”mydb”,charset=”utf8”)
使用cursor()方法建立一個遊標物件cursor
Cursor = db.cursor()
使用execute()方法執行SQL查詢
Cursor.execute(SQL語句)
處理結果(執行增、刪、改和查的所有操作)
關閉資料庫
Db.close()
Cursor.fetchone() 獲取一條資訊 可遍歷
Cursor.fetchall() 獲取全部資訊
進行操作是使用try: except Exception as e: 檢查異常
使用 db.commit() db.rollback() 來進行提交和回滾