python連接mysql數(shù)據(jù)庫并讀取數(shù)據(jù)的實現(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 = 端口號, user = ’用戶名’, passwd = ’用戶密碼’, db = ’數(shù)據(jù)庫名稱’, charset = ’utf8’ )
注:
查看本機IP地址:cmd輸入:ipconfig,IPv4 地址
pymysql.Connect參數(shù)中的 host 服務(wù)器地址,本機可用’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: # 使用異常處理,以防程序無法正常運行 cur.execute(sql) data = df(cur.fetchall(), columns = [col[0] for col in cur.description]) except Exception as e: conn.rollback() # 發(fā)生錯誤時回滾 print(’事務(wù)處理失敗’, e)else: # conn.commit() # 事務(wù)提交 print(’事務(wù)處理成功’, cur.rowcount)cur.close()
注:
read_sql、cursor游標(biāo)區(qū)別:
read_sql :只能執(zhí)行查詢數(shù)據(jù) cursor游標(biāo) :可以執(zhí)行查詢、插入、更新、刪除等操作cur.execute(sql) :
執(zhí)行具體數(shù)據(jù)庫的操作cur.fetchone() :
獲取單條數(shù)據(jù)cur.fetchmany(3) :
獲取前3條數(shù)據(jù)cur.fetchall() :
獲取所有數(shù)據(jù)查詢結(jié)果中含字段名稱:
# 法1: cur = conn.cursor(cursor = pymysql.cursors.DictCursor) # 設(shè)置成DictCursor,結(jié)果包含字段名稱 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() :
插入、更新、刪除等操作需用該語句;查詢、創(chuàng)建數(shù)據(jù)庫、數(shù)據(jù)表則不需要cur.rowcount :
返回執(zhí)行的操作條數(shù)4、關(guān)閉數(shù)據(jù)庫
conn.close()
到此這篇關(guān)于python連接mysql數(shù)據(jù)庫并讀取數(shù)據(jù)的實現(xiàn)的文章就介紹到這了,更多相關(guān)python連接mysql內(nèi)容請搜索好吧啦網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持好吧啦網(wǎng)!
相關(guān)文章:
1. Warning: require(): open_basedir restriction in effect,目錄配置open_basedir報錯問題分析2. ASP.NET Core 5.0中的Host.CreateDefaultBuilder執(zhí)行過程解析3. ASP調(diào)用WebService轉(zhuǎn)化成JSON數(shù)據(jù),附j(luò)son.min.asp4. SharePoint Server 2019新特性介紹5. ASP中常用的22個FSO文件操作函數(shù)整理6. React+umi+typeScript創(chuàng)建項目的過程7. php網(wǎng)絡(luò)安全中命令執(zhí)行漏洞的產(chǎn)生及本質(zhì)探究8. 無線標(biāo)記語言(WML)基礎(chǔ)之WMLScript 基礎(chǔ)第1/2頁9. 三個不常見的 HTML5 實用新特性簡介10. php測試程序運行速度和頁面執(zhí)行速度的代碼
