码迷,mamicode.com
首页 > 数据库 > 详细

python—mysql数据库读取表1获取name作为参数,传入访问表2获取age,结果存入excel

时间:2020-07-06 12:53:50      阅读:86      评论:0      收藏:0      [点我收藏+]

标签:com   where   utf8   ***   转化   nec   读取   har   lis   

#访问数据库users表读取name
#name作为参数,传递查询logininfor表对应的年龄age,并将结果存为excel
import pymysql
import pandas as pd
import openpyxl
coon=pymysql.connect(host=‘127.0.0.1‘,
user=‘root‘,
password=‘****‘,
port=3306,
db=‘tone‘,
charset=‘utf8‘,
autocommit=True)
cur=coon.cursor()
sql = ‘select * from users‘
cur.execute(sql)
data=cur.fetchall()
#将二维元组转化为dataframe
#结果二维元组((1, ‘lily‘), (2, ‘lucy‘), (3, ‘lilei‘))
data_df=pd.DataFrame(list(data))
print(data)
dict_result={}
#获取dataframe中名称列
for i in data_df[1]:
#将名称作为参数传入,查询对应的age值
sql = ‘select age from logininfo where name = %s‘
cur.execute(sql,(i,))
data_age = cur.fetchall()
#将结果二维元组((20,),)转化为dataframe格式
data_result=pd.DataFrame(list(data_age))
#将name与age组合为字典存储
for j in list(data_age):
dict_result[i]=j[0]

#将字典转换为dataframe,注意要指定index=0,否则报错
result_df=pd.DataFrame(dict_result,index=[0])
#将dataframe存入excel表格,index=False不保存dataframe 中的index
path=r‘/Users/**/PycharmProjects/class/pyclass1/others/file/result.xlsx‘
result_df.to_excel(path,index=False)

python—mysql数据库读取表1获取name作为参数,传入访问表2获取age,结果存入excel

标签:com   where   utf8   ***   转化   nec   读取   har   lis   

原文地址:https://www.cnblogs.com/wenchengqingfeng/p/13254033.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!