запрос не возвращает никаких результатов в Python - PullRequest
0 голосов
/ 27 мая 2019

Часть кода SQL работает в моем SQL, когда %s заменяется желаемым временем начала.Я попробовал все, и кажется, что я не могу получить результаты в Python - возвращаемое значение [].

Я пытался переписать WHERE from (Convert_TZ(Tablex, 'TZ1', 'TZ2') Between 'Time1' and 'time2', так как я не видел, чтобы запросы использовали междув питоне раньше.

import mysql.connector
import xlsxwriter
import datetime


while True:
    try:
        LB = input('Enter Lower Bound date/time in YYMMDD hhmm >>> ')
        YY = '20' + LB[:2]
        MM = LB[2:4]
        DD = LB[4:6]
        hh = LB[7:9]
        mm = LB[9:]
        LB_date = datetime.datetime(int(YY), int(MM), int(DD), int(hh), int(mm))
        print(LB_date)
        break
    except ValueError:
        print('Invalid Entry')
        print('Date/Time must be in YYMMDD HHMM format')
        print('\n')

while True:
    try:
        UB = input('Enter Upper Bound date/time in YYMMDD hhmm >>> ')
        if UB.upper() == 'NOW':
            UB_date = UB.upper()
        YY = '20' + LB[:2]
        MM = LB[2:4]
        DD = LB[4:6]
        hh = LB[7:9]
        mm = LB[9:]
        UB_date = datetime.datetime(int(YY), int(MM), int(DD), int(hh), int(mm))
        break
    except ValueError:
        print('Invalid Entry')
        print('Date/Time must be in YYMMDD HHMM format')
        print('\n')

us_cnx = mysql.connector.connect(user='user',
                                password='password',
                                host='host',
                                port=1234,
                                database='schema')

us_cursor = us_cnx.cursor(buffered=True)

if UB_date == 'NOW':
    us_query = ("""
                    SELECT 
                        distinct(parent.name),
                        CONVERT_TZ(parent.created, 'GMT', 'US/Pacific'),
                        nc.description,
                        nc.createdby,
                        thingdata.valuetext,
                        actor.name,
                        nca.disposition,
                        nca.description, 
                        nc.closedby, 
                       convert_tz(nc.closed, 'GMT', 'US/Pacific')
                    FROM
                        thing child
                        LEFT JOIN 
                        thing parent ON parent.id = child.parentid
                         LEFT JOIN
                        nc ON nc.thingid = parent.id
                            LEFT JOIN
                        thingdata ON thingdata.thingid = parent.id
                            JOIN
                        actor ON parent.actorcreatedby = actor.id
                        left join 
                        ncaction nca on nca.ncid = nc.id
                    WHERE
                        parent.actorcreatedby IN ( 
                        '2624519', 
                        '2624520', 
                        '2624521', 
                        '2624522', 
                        '2624523', 
                        '2624524', 
                        '2624525',
                        '2624526', 
                        '2624527' )
                        AND nc.createdby like 'actor'
                        AND nc.description != 'NULL'
                        AND parent.created > CONVERT_TZ(%s, 'US/Pacific', 'GMT')
                        AND parent.created < convert_TZ(NOW(), 'US/Pacific', 'GMT')
                        AND thingdata.taskid IN ('1616757')



                 """)
    us_cursor.execute(us_query, (LB_date,))

else:
    us_query = ("""
                    SELECT 
                        distinct(parent.name),
                        CONVERT_TZ(parent.created, 'GMT', 'US/Pacific'),
                        nc.description,
                        nc.createdby,
                        thingdata.valuetext,
                        actor.name,
                        nca.disposition,
                        nca.description, 
                        nc.closedby, 
                       convert_tz(nc.closed, 'GMT', 'US/Pacific')
                    FROM
                        thing child
                        LEFT JOIN 
                        thing parent ON parent.id = child.parentid
                         LEFT JOIN
                        nc ON nc.thingid = parent.id
                            LEFT JOIN
                        thingdata ON thingdata.thingid = parent.id
                            JOIN
                        actor ON parent.actorcreatedby = actor.id
                        left join 
                        ncaction nca on nca.ncid = nc.id
                    WHERE
                        parent.actorcreatedby IN ( 
                        '2624519', 
                        '2624520', 
                        '2624521', 
                        '2624522', 
                        '2624523', 
                        '2624524', 
                        '2624525',
                        '2624526', 
                        '2624527' )
                        AND nc.createdby like 'ignition-gf1-bm-tag4-prod'
                        AND nc.description != 'NULL'
                        AND parent.created > CONVERT_TZ(%s, 'US/Pacific', 'GMT')
                        AND parent.created < convert_TZ(%s, 'US/Pacific', 'GMT')
                        AND thingdata.taskid IN ('1616757')
                 """)
    us_cursor.execute(us_query, (LB_date, UB_date))
us_results = us_cursor.fetchall()
us_cursor.close()
us_cnx.close()
for i in range(len(us_results)):
                us_results.append((us_results[i][0], us_results[i][1], us_results[i][2], us_results[i][3],
                                   us_results[i][4], us_results[i][5], us_results[i][6], us_results[i][7],
                                   us_results[i][8], us_results[i][9]))
print(us_results)

workbook = xlsxwriter.Workbook('U-S.xlsx')
time_format = workbook.add_format({'num_format': 'yyyy-mm-dd hh:mm:ss'})
counter_format = workbook.add_format({'num_format': 'hh:mm:ss'})

worksheet = workbook.add_worksheet()
Headers = ('Serial', 'Created PST', 'Defect', 'NC Created By', 'US ID', 'Created By',
           'Disposition', 'Rework Notes', 'NC Closed By', 'NC Closed PST')
for i in range(len(Headers)):
    worksheet.write(0, i, Headers[i])
xlsx_row = 1
for row in us_results:
    for j in range(len(Headers)):

        worksheet.add_table(j, {'style': 'Table Style Dark 11'})
        worksheet.set_column(j, 32)
        if j in [1, 9]:
            worksheet.write(xlsx_row, j, row[j], time_format)
        else:
            worksheet.write(xlsx_row, j, row[j])
    xlsx_row += 1


workbook.close()

Все работает как положено, но ничего не возвращается в US_results (просто печатается в консоли как []), а в файле excel есть только заголовки.

...