pandas如何讀取mysql數(shù)據(jù)
更新時(shí)間:2022年12月17日 15:17:41 作者:會(huì)發(fā)paper的學(xué)渣
這篇文章主要介紹了pandas如何讀取mysql數(shù)據(jù)問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
pandas讀取mysql數(shù)據(jù)
def get_data():
conn = pymysql.connect(host=RSYS_HOST,
port=RSYS_PORT,
user=RSYS_USER,
passwd=RSYS_PASSWORDD,
db=RSYS_DB_NAME,
charset='utf8')
results = None
try:
read_result = pd.read_sql(sql, conn)
result_json = json.loads(read_result.reset_index().to_json(orient='records', force_ascii=False))
logger.info(sql)
return result_json
except Exception as e:
# 發(fā)生錯(cuò)誤時(shí)回滾
logger.error("Error: unable to fecth data: %s,%s" % (repr(e), sql))
conn.rollback()
finally:
conn.close()
return resultspandas讀取mysql數(shù)據(jù)到DataFrame
方法一
#-*- coding:utf-8 -*-
from sqlalchemy import create_engine
class mysql_engine():
? ? user='******'
? ? passwd='******'
? ? host='******'
? ? port = '******'
? ? db_name='******'
? ? engine = create_engine('mysql://{0}:{1}@{2}:{3}/{4}?charset=utf8'.format(user,passwd,host,port,db_name))
def get_data(sql):
? ? pg_enine=mysql_engine()
? ? try:
? ? ? ? with pg_enine.engine.connect() as con, con.begin():
? ? ? ? ? ? df=pd.read_sql(sql,con)# 獲取數(shù)據(jù)
? ? ? ? con.close()
? ? except:
? ? ? ? df=None
? ? return df方法二
conn = MySQLdb.connect(host="******",user="******",passwd="******",db='******',port = ******,charset="utf8") sql = "select * from ****** limit 3" df = pd.read_sql(sql,conn,index_col="id") print df
pd 1.9以后的版本,除了sqllite,均需要通過(guò)sqlalchemy來(lái)設(shè)置
總結(jié)
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
相關(guān)文章
使用Python實(shí)現(xiàn)炫酷的數(shù)據(jù)動(dòng)態(tài)圖大全
數(shù)據(jù)可視化是通過(guò)圖形、圖表、地圖等可視元素將數(shù)據(jù)呈現(xiàn)出來(lái),以便更容易理解、分析和解釋,它是將抽象的數(shù)據(jù)轉(zhuǎn)化為直觀形象的過(guò)程,本文給大家介紹了使用Python實(shí)現(xiàn)炫酷的數(shù)據(jù)動(dòng)態(tài)圖大全,需要的朋友可以參考下2024-06-06
python操作SqlServer獲取特定表的所有列名(推薦)
這篇文章主要介紹了python操作SqlServer獲取特定表的所有列名,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2022-08-08
使用wxPython和pandas模塊生成Excel文件的代碼實(shí)現(xiàn)
在Python編程中,有時(shí)我們需要根據(jù)特定的數(shù)據(jù)生成Excel文件,本文將介紹如何使用wxPython和pandas模塊來(lái)實(shí)現(xiàn)這個(gè)目標(biāo),文中通過(guò)代碼示例給大家講解的非常詳細(xì),具有一定的參考價(jià)值,需要的朋友可以參考下2024-05-05
Python 使用type來(lái)定義類(lèi)的實(shí)現(xiàn)
今天小編就為大家分享一篇Python 使用type來(lái)定義類(lèi)的實(shí)現(xiàn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2019-11-11
python爬蟲(chóng)超時(shí)的處理的實(shí)例
今天小編就為大家分享一篇python爬蟲(chóng)超時(shí)的處理的實(shí)例,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧2018-12-12
python executemany的使用及注意事項(xiàng)
這篇文章主要介紹了python executemany的使用及注意事項(xiàng),非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下2017-03-03

