1、安裝pymysql包
1
|
pip install pymysql |
注:
MySQLdb只支持python2,pymysql支持python3
2、連接數據
1
2
3
4
5
6
7
8
9
10
11
|
import pymysql import pandas as pd from pandas import DataFrame as df conn = pymysql.Connect( host = 'IP地址' , port = 端口號, user = '用戶名' , passwd = '用戶密碼' , db = '數據庫名稱' , charset = 'utf8' ) |
注:
查看本機IP地址:cmd輸入:ipconfig,IPv4 地址
pymysql.Connect參數中的 host 服務器地址,本機可用'localhost'
3、讀取數據
(1)使用read_sql讀取數據
1
2
|
sql = 'select * from testa' data = pd.read_sql(sql, conn) |
(2)使用cursor讀取數據
1
2
3
4
5
6
7
8
9
10
11
12
|
sql = 'select * from testa' cur = conn.cursor() try : # 使用異常處理,以防程序無法正常運行 cur.execute(sql) data = df(cur.fetchall(), columns = [col[ 0 ] for col in cur.description]) except Exception as e: conn.rollback() # 發生錯誤時回滾 print ( '事務處理失敗' , e) else : # conn.commit() # 事務提交 print ( '事務處理成功' , cur.rowcount) cur.close() |
注:
read_sql、cursor游標區別:
- read_sql :只能執行查詢數據
- cursor游標 :可以執行查詢、插入、更新、刪除等操作
cur.execute(sql) :
- 執行具體數據庫的操作
cur.fetchone() :
- 獲取單條數據
cur.fetchmany(3) :
- 獲取前3條數據
cur.fetchall() :
- 獲取所有數據
查詢結果中含字段名稱:
1
2
3
4
5
6
7
8
9
|
# 法1: cur = conn.cursor(cursor = pymysql.cursors.DictCursor) # 設置成DictCursor,結果包含字段名稱 cur.execute(sql) data = df(cur.fetchall()) # 法2: cur = conn.cursor() cur.execute(sql) data = df(cur.fetchall(),columns = [col[ 0 ] for col in cur.description]) |
conn.commit() :
- 插入、更新、刪除等操作需用該語句;查詢、創建數據庫、數據表則不需要
cur.rowcount :
- 返回執行的操作條數
4、關閉數據庫
1
|
conn.close() |
到此這篇關于python連接mysql數據庫并讀取數據的實現的文章就介紹到這了,更多相關python連接mysql內容請搜索服務器之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持服務器之家!
原文鏈接:https://blog.csdn.net/weixin_40012554/article/details/108734167