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 pd from pandas import DataFrame as df conn = pymysql.Connect( host = 'IP地址', port = 端口號(hào), user = '用戶名', passwd = '用戶密碼', db = '數(shù)據(jù)庫(kù)名稱', 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í)行查詢數(shù)據(jù)
- cursor游標(biāo) :可以執(zhí)行查詢、插入、更新、刪除等操作
cur.execute(sql) :
- 執(zhí)行具體數(shù)據(jù)庫(kù)的操作
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() :
- 插入、更新、刪除等操作需用該語(yǔ)句;查詢、創(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)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python如何讀取MySQL數(shù)據(jù)庫(kù)表數(shù)據(jù)
- python3 pandas 讀取MySQL數(shù)據(jù)和插入的實(shí)例
- Python3讀取Excel數(shù)據(jù)存入MySQL的方法
- 使用python的pandas庫(kù)讀取csv文件保存至mysql數(shù)據(jù)庫(kù)
- python讀取word文檔,插入mysql數(shù)據(jù)庫(kù)的示例代碼
- python讀取mysql數(shù)據(jù)繪制條形圖
- Python 讀取千萬(wàn)級(jí)數(shù)據(jù)自動(dòng)寫入 MySQL 數(shù)據(jù)庫(kù)
相關(guān)文章
python的unittest測(cè)試類代碼實(shí)例
這篇文章主要介紹了python的unittest測(cè)試類代碼實(shí)例,具有一定參考價(jià)值,需要的朋友可以了解下。2017-12-12
python語(yǔ)法教程之def()函數(shù)定義及用法
函數(shù)是組織好的,可重復(fù)使用的,用來(lái)實(shí)現(xiàn)單一,或相關(guān)聯(lián)功能的代碼段,下面這篇文章主要給大家介紹了關(guān)于python語(yǔ)法教程之def()函數(shù)定義及用法的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-01-01
Python的Flask項(xiàng)目中獲取請(qǐng)求用戶IP地址 addr問(wèn)題
這篇文章主要介紹了Python的Flask項(xiàng)目中獲取請(qǐng)求用戶IP地址 addr問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
python?windows安裝cuda+cudnn+pytorch教程
這篇文章主要介紹了python?windows安裝cuda+cudnn+pytorch教程,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-05-05

