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

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

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)#读取数据

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5689519.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存