您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python连接数据库查询结果保存excl

bubuko 2022/1/25 19:03:50 python 字数 2472 阅读 798 来源 http://www.bubuko.com/infolist-5-1.html

pymysql 操作mysql数据库 openpyxl 操作excel表 连上mysql操作: 1、打开数据库 import pymysql db=pymysql.connect(host,user,password,database) 2、使用cursor()方法创建一个游标对象 cursor=d ...

pymysql------操作mysql数据库

openpyxl------操作excel表

 

连上mysql操作:

1、打开数据库

import pymysql

db=pymysql.connect(host,user,password,database)

2、使用cursor()方法创建一个游标对象

cursor=db.cursor()

3、执行操作

a、数据库插入 

try:

  curcor.excute(sql)

  db.commit()

except:

  db.rollback()

b、数据库查询(fetchone()--该方法获取下一个查询结果集。结果集是一个对象、fetchall()-----接收全部的返回结果行.)

cursor.excute(sql)

result=cursor.fetchall() or result=cursor.fetchone()

 

 

操作excel 表

 

import openpyxl

wb=openpyxl.load_workbook("filename.xlsx")

sheet=wb[‘sheetname‘]

row=sheet.max_row

sheet.cell(i,j).value

wb.save("filename.xlsx")

 

 

import pymysql
import openpyxl

hostIP_T4=‘172.16.1.210‘
user_T4=‘ttd‘
password_T4=‘ROOT@mwteck123‘
database_T4=‘ttd‘
db_T4=pymysql.connect(hostIP_T4,user_T4,password_T4,database_T4)
cursor_T4=db_T4.cursor()
evid_sql="select uuid from ev_info where projectId=584056423265083392 and evOrder=%s"
wb=openpyxl.load_workbook(‘怡廉苑.xlsx‘)
sheet=wb[‘Sheet1‘]
row=sheet.max_row
for i in range(1,row):
    temp=sheet.cell(i+1,1).value
    print(temp)
    try:
        #temchange=temp.replace(‘-‘,‘#楼‘,1).replace(‘1-‘,‘一单元‘,1)
        #temchange=temchange.replace(‘2-‘,‘二单元‘,1)
        #temchange=temchange+‘梯‘
        #sheet.cell(i+1,1).value=temchange
        cursor.execute(evid_sql,temp)
        result=cursor.fetchall()
        print(result)
        sheet.cell(i+1,5).value=str(result[0][0])
    except Exception as e:
        print(e)
wb.save(‘怡廉苑3.xlsx‘)


 

Python连接数据库查询结果保存excl

原文:https://www.cnblogs.com/ada-luo/p/14866625.html


如果您也喜欢它,动动您的小指点个赞吧

除非注明,文章均由 laddyq.com 整理发布,欢迎转载。

转载请注明:
链接:http://laddyq.com
来源:laddyq.com
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。


联系我
置顶