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


  • 相关阅读:
    python之ConfigParser模块
    python之os模块
    python之cx_oracle模块
    python之zipfile模块
    python之sys模块
    python相关模块链接
    Server.UrlPathEncode和Server.UrlEncode的区别
    设置或者得到CheckBoxList选中了的值
    一些数据格式化-Eval( " ")和DataBinder.Eval(Container.DataItem, " ")的区别及用法
    ADO中数据库连接字符串的几种写法
  • 原文地址:https://www.cnblogs.com/ada-luo/p/14866625.html
Copyright © 2011-2022 走看看