python 連接 mysql 資料庫并讀取資料
1、安裝pymysql包
pip install pymysql
注:
- MySQLdb只支持python2,pymysql支持python3
2、連接資料
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讀取資料
sql = 'select * from testa'
data = pd.read_sql(sql, conn)
(2)使用cursor讀取資料
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: 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、關閉資料庫
conn.close()
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/123882.html
標籤:其他
上一篇:Python基本資料型別
