栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

pandas读取数据库mysql及处理where in 【List,Array】问题

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

pandas读取数据库mysql及处理where in 【List,Array】问题

1.pandas读取数据库mysql
#jupyter notebook安装pymysql 
!pip install pymysql
#用到的模块create_engine
 import pandas as pd
 from sqlalchemy import create_engine
 
 # MySQL的用户:root, 密码:123456, 端口:3306,数据库:test
engine =create_engine('mysql+pymysql://root:123456@localhost:3306/test')
# 查询语句
sql = ''' select * from table ;'''
 # read_sql_query的两个参数: sql语句, 数据库连接
df = pd.read_sql_query(sql, engine)

 # 新建pandas中的Dataframe, 只有id,num两列
df = pd.Dataframe({'id': [1, 2, 3, 4], 'name': ['zhangsan', 'lisi', 'wangwu', 'zhuliu']})
# 将新建的Dataframe储存为MySQL中的数据表,储存index列
df.to_sql('mydf', engine, index=True)

读取数据的几种方式
==============================================================================
#第一种读取数据方式  ----pandas 如上
#第二种读取数据方式  ----engine.execute(sql)
from sqlalchemy import create_engine

engine = create_engine('mysql+pymysql://root:123456@localhost:3306/test')
sql = "DROp TABLE IF EXISTS example"
engine.execute(sql)

#第三种读取数据方式  ----pymysql
import pymysql
from sqlalchemy import create_engine

conn = pymysql.connect(host='127.0.0.1', port=3306, user='root', passwd='123456', db='test')
sql = "DROp TABLE IF EXISTS test_input"# sql语句
cursor = conn.cursor()
cursor.execute(sql)
2.将Dataframe存入mysql
# 读取本地CSV文件
df = pd.read_csv("example.csv", sep=',')
df
# 将新建的Dataframe储存为MySQL中的数据表,不储存index列(index=False)
# if_exists:
# 1.fail:如果表存在,啥也不做
# 2.replace:如果表存在,删了表,再建立一个新表,把数据插入
# 3.append:如果表存在,把数据插入,如果表不存在创建一个表!!
pd.io.sql.to_sql(df, 'example', con=engine, index=False, if_exists='replace')
# df.to_sql('example', con=engine,  if_exists='replace')这种形式也可以
3.where in 对列表(list,array)问题
#假如 你要执行这个语句
select * from server where ip in (....)
ip_list=['0.0.0.0','1.1.1.1','2.2.2.2',.......]#老多了
new_list=','.join(["'%s'" % item for item in ip_list])
# "'0.0.0.0','1.1.1.1','2.2.2.2'........"

import pandas as pd
from sqlalchemy import create_engine
#建立连接
engine =create_engine('mysql+pymysql://root:123456@localhost:3306/test')
sql_2='''select * from server where ip in ({});'''.format(new_list)# 查询语句
df=pd.read_sql_query(sql_2, engine)#读取数据

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/689009.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号