python連接mysql數(shù)據(jù)庫(kù)并讀取數(shù)據(jù)的實(shí)現(xiàn)
1、安裝pymysql包
pip install pymysql
注:MySQLdb只支持python2,pymysql支持python3
2、連接數(shù)據(jù)
import pymysql import pandas as pdfrom pandas import DataFrame as dfconn = pymysql.Connect( host = ’IP地址’, port = 端口號(hào), user = ’用戶(hù)名’, passwd = ’用戶(hù)密碼’, db = ’數(shù)據(jù)庫(kù)名稱(chēng)’, charset = ’utf8’ )
注:
查看本機(jī)IP地址:cmd輸入:ipconfig,IPv4 地址
pymysql.Connect參數(shù)中的 host 服務(wù)器地址,本機(jī)可用’localhost’
3、讀取數(shù)據(jù)
(1)使用read_sql讀取數(shù)據(jù)
sql = ’select * from testa’data = pd.read_sql(sql, conn)
(2)使用cursor讀取數(shù)據(jù)
sql = ’select * from testa’cur = conn.cursor() try: # 使用異常處理,以防程序無(wú)法正常運(yùn)行 cur.execute(sql) data = df(cur.fetchall(), columns = [col[0] for col in cur.description]) except Exception as e: conn.rollback() # 發(fā)生錯(cuò)誤時(shí)回滾 print(’事務(wù)處理失敗’, e)else: # conn.commit() # 事務(wù)提交 print(’事務(wù)處理成功’, cur.rowcount)cur.close()
注:
read_sql、cursor游標(biāo)區(qū)別:
read_sql :只能執(zhí)行查詢(xún)數(shù)據(jù) cursor游標(biāo) :可以執(zhí)行查詢(xún)、插入、更新、刪除等操作cur.execute(sql) :
執(zhí)行具體數(shù)據(jù)庫(kù)的操作cur.fetchone() :
獲取單條數(shù)據(jù)cur.fetchmany(3) :
獲取前3條數(shù)據(jù)cur.fetchall() :
獲取所有數(shù)據(jù)查詢(xún)結(jié)果中含字段名稱(chēng):
# 法1: cur = conn.cursor(cursor = pymysql.cursors.DictCursor) # 設(shè)置成DictCursor,結(jié)果包含字段名稱(chēng) 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() :
插入、更新、刪除等操作需用該語(yǔ)句;查詢(xún)、創(chuàng)建數(shù)據(jù)庫(kù)、數(shù)據(jù)表則不需要cur.rowcount :
返回執(zhí)行的操作條數(shù)4、關(guān)閉數(shù)據(jù)庫(kù)
conn.close()
到此這篇關(guān)于python連接mysql數(shù)據(jù)庫(kù)并讀取數(shù)據(jù)的實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)python連接mysql內(nèi)容請(qǐng)搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. 如何用 Python 制作一個(gè)迷宮游戲2. 部署vue+Springboot前后端分離項(xiàng)目的步驟實(shí)現(xiàn)3. Django如何使用asyncio協(xié)程和ThreadPoolExecutor多線(xiàn)程4. vue組件庫(kù)的在線(xiàn)主題編輯器的實(shí)現(xiàn)思路5. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過(guò)程6. idea設(shè)置自動(dòng)導(dǎo)入依賴(lài)的方法步驟7. Python安裝并操作redis實(shí)現(xiàn)流程詳解8. 網(wǎng)頁(yè)中img圖片使用css實(shí)現(xiàn)等比例自動(dòng)縮放不變形(代碼已測(cè)試)9. JavaScript實(shí)現(xiàn)組件化和模塊化方法詳解10. PHP安全-跨站腳本攻擊
