zoukankan      html  css  js  c++  java
  • Python连接数据库查询结果保存excl

    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')


  • 相关阅读:
    Android应用中使用自定义文字
    Linux下diff使用简介
    Android扫描SD卡中的文件
    onActivityResult不起作用?可能是和你的launchMode有关!
    修改SlidingMenu,使其能够完美运行
    eclipse快捷键说明
    XP下Virtualbox虚拟Ubuntu共享文件夹设置
    记一次调用RefreshObjectCaches刷新节点上的文件内容
    idea快捷键之遍历
    word转pdf
  • 原文地址:https://www.cnblogs.com/ada-luo/p/14866625.html
Copyright © 2011-2022 走看看