python—mysql数据库读取表1获取name作为参数,传入访问表2获取age,结果存入excel,,#访问数据库user
python—mysql数据库读取表1获取name作为参数,传入访问表2获取age,结果存入excel,,#访问数据库user
#访问数据库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
相关内容
- Python-同时匹配邮箱和电话号码的正则表达式,,同时匹
- Python爬虫之使用celery加速爬虫,,??celery是一
- python中文件的管理和oc中的文件管理,,Python中对文件
- python_selenium 之yaml文件读取(以读取元素信息为例),
- python学习之数据类型—元组tuple,,元组:tuple1、
- Python3正则表达式清洗Excel文档,,本项目中虽然数据量不
- ubuntu16 下安装python3.6 和Anaconda3,,1.Python3.
- python慎用os.getcwd() ,除非你知道【文件路径与当前工作
- python中定义函数时,self怎么理解:,,在定义方法的时
- Python字典和集合,,Python字典(D
评论关闭