pandas数据保存至Mysql数据库
pandas数据保存至Mysql数据库
import pandas as pd from sqlalchemy import create_engine host = '127.0.0.1' port = 3306 db = 'test' user = 'root' password = '********' engine = create_engine(str(r'mysql mysqldb://%s:' '%s' '@%s/%s') % (user, password, host, db)) try: df = pd.DataFrame([[1,'x'],[2,'y']],columns=list('ab')) df.to_sql('test1',con=engine,if_exists='replace',index=False) except Exception as e: print(e)
to_sql参数
参数: |
|
---|---|
举: |
|
参考链接:http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.to_sql.html
应用场景
1建立tcp一次长连接,发送数据端:每隔5s发送一次json数据,接受数据端:接收数据,进行数据处理,存储数据
server
import socket import pandas as pd from sqlalchemy import create_engine sk = socket.socket() sk.bind(('127.0.0.1',8000)) sk.listen(2) con,addr = sk.accept() # print(addr,con) engine = create_engine('mysql+pymysql://root:@127.0.0.1:3306/db1') while True: msg = con.recv(8048).decode() df = pd.read_json(msg,dtype={'code':'str'}) # 删除parentId列 df.drop(['parentId'],axis=1,inplace=True) # 修改id为cid df1 = df.rename(columns={'id':'cid'}) # print(df1) try: # df = pd.DataFrame([[1,'x'],[2,'y']],columns=list('ab')) df1.to_sql('test1',con=engine,if_exists='append',index=False) except Exception as e: print(e)
client
import socket import time import re import requests import json import pandas as pd sk = socket.socket() sk.connect(('127.0.0.1',8000)) url = 'https://www.lagou.com/lbs/getAllCitySearchLabels.json' heards = { 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3452.0 Safari/537.36' } cont = requests.get(url=url, headers=heards).text while True: cont1 = re.findall('\[.+?\]', cont) for i in cont1: sk.send(i.encode('utf8')) time.sleep(5)