python查询mysql数据库的问题

查看:108
本文介绍了python查询mysql数据库的问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

使用excle作为配置文件存储数据库链接相关参数;

想要达到的目的是,每天执行脚本检查数据量,存入另一张excle
现在遇到的问题是,查第一个数据库没问题,到查第二个数据开始返回的执行结果还是第一个数据库的结果。。。我把结果答应出来看是这样的:

以下是代码:


#-*-coding:utf_8-*-
import xlrd  #加载excle读取方法
import xlwt  #加载excle写入方法
import mysql.connector as lj  #加载mysql控件
import datetime #加载日期方法

def db_src():
    data = xlrd.open_workbook('test.xlsx')  #test中存数据库链接信息
    table = data.sheets()[0] #获取excle的第一个sheets
    nrows = table.nrows  # 获取行数
    tmp = {}  #初始化空字典
    temp = tmp.fromkeys([x for x in range(1,nrows)],[])  #序列化一个字典集{key:[value1,value2..]}
    for i in range(1,nrows):
        data_row = table.row_values(i)  # 获取整行的值
        host = data_row[1]    #读取行中的每列记录
        user = data_row[2]
        password = data_row[3]
        port = data_row[4]
        database = data_row[5]
        conn = lj.connect(             #连接数据库
            user=user,
            password=password,
            port=port,
            host=host,
            database=database)
        cur = conn.cursor()  #创建游标
        today = datetime.date.today()  #当前日期
        yestday = today - datetime.timedelta(days=1)
        sql_1 = "select count(1) from t_vehicle%s"%today.strftime('%Y%m%d') #查询当天
        sql_2 = "select count(1) from t_vehicle%s"%yestday.strftime('%Y%m%d')#查询前天
        sql_3 = "select code_,name_ from t_channel t1 where t1.ID_ not in (select HostChannelId_ from t_vehicle%s)"%yestday.strftime('%Y%m%d')
                #查询昨天无数据车道信息
        cur.execute(sql_1)  #执行sql_1
        a = (cur.fetchall())   #获取执行结果
        temp[i].append(a[0][0]) #将查询结果放入字典中
        cur.execute(sql_2)  # 执行sql_2
        a = cur.fetchall()    # 获取执行结果
        temp[i].append(a[0][0])
        cur.execute(sql_3)  # 执行sql_3
        a = cur.fetchall()  #type(a) = list
        code = []
        name = []
        for t in range(len(a)):
            code.append(a[t][0])
            name.append(a[t][1])   #车道编号名称分别生成两个列表
        temp[i].append(code)  # 获取执行结果
        temp[i].append(name)  # 获取执
        # 行结果
        # print('已完成对%s的查询,当前正在关闭与该数据库的链接。。。请稍后。。。'%data_row[0])
        conn.close()
        cur.close()
    # print('所有脚本检查完毕,准备写入excle')

    f = xlwt.Workbook()
    sheet = f.add_sheet('sheet1', cell_overwrite_ok=True)  # 创建sheet
    sheet.write(0, 0, '服务器名称') # 初始化标题
    sheet.write(0, 1, '当前总量')  # 初始化标题
    sheet.write(0, 2, '昨天总量')  # 初始化标题
    sheet.write(0, 3, '无数据1')  # 初始化标题
    sheet.write(0, 4, '无数据2')  # 初始化标题
    sheet.write(0, 5, '查询结果5')  # 初始化标题
    # for k,v in temp.items():
    #     for j in range(len(v)):
    #         print(k,j+1,(v[j]))
    for i_1 in range(1,nrows):
        ex1=temp[i_1][0]
        sheet.write(i_1,1,ex1 )
        ex2=temp[1][1]
        sheet.write(i_1,2,ex2)
        ex3='\n'.join(temp[1][2])
        sheet.write(i_1,3,ex3)
        ex4='\n'.join(temp[1][3])
        sheet.write(i_1,4,ex4)
    f.save('巡检结果.xls')


db_src()

解决方案

数据库查询结果没有问题,但是你的temp字典中每个键所指向的是同一个列表,我在python2.7和3.6上的测试结果一致。

>> tmp={}
>> tmp = tmp.fromkeys([x for x in range(1,3)],[])
>> tmp
{1: [], 2: []}
>>> tmp[1].append(1)
>>> tmp
{1: [1], 2: [1]}

可以修改为:

temp = {x:[] for x in range(1,3)}

我用你的代码测试了一下,修正这个问题前:

local.test:3306@test1 root niconiconi
{1: [999L], 2: [999L]}
{1: [999L, 999L], 2: [999L, 999L]}
{1: [999L, 999L, ['1', '2'], ['a', 'b']], 2: [999L, 999L, ['1', '2'], ['a', 'b']]}
local.test:3306@test2 root niconiconi
{1: [999L, 999L, ['1', '2'], ['a', 'b'], 666L], 2: [999L, 999L, ['1', '2'], ['a', 'b'], 666L]}
{1: [999L, 999L, ['1', '2'], ['a', 'b'], 666L, 666L], 2: [999L, 999L, ['1', '2'], ['a', 'b'], 666L, 666L]}
{1: [999L, 999L, ['1', '2'], ['a', 'b'], 666L, 666L, ['1', '2'], ['a', 'b']], 2: [999L, 999L, ['1', '2'], ['a', 'b'], 666L, 666L, ['1', '2'], ['a', 'b']]}

修正问题后:

local.test:3306@test1 root niconiconi
{1: [999L], 2: []}
{1: [999L, 999L], 2: []}
{1: [999L, 999L, ['1', '2'], ['a', 'b']], 2: []}
local.test:3306@test2 root niconiconi
{1: [999L, 999L, ['1', '2'], ['a', 'b']], 2: [666L]}
{1: [999L, 999L, ['1', '2'], ['a', 'b']], 2: [666L, 666L]}
{1: [999L, 999L, ['1', '2'], ['a', 'b']], 2: [666L, 666L, ['1', '2'], ['a', 'b']]}

追加:向excel里设值的时候应该是temp[i_1][1]而不是temp[1][1]吧,请确认一下。

这篇关于python查询mysql数据库的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆