#访问数据库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