jeudi 29 juillet 2021

Query results using odbc in python

import pyodbc as odbc

Driver = 'SQL Server'
server_name = ''
database_name = ''

conn = odbc.connect(f"""
    Driver=};
    Server={server_name};
    Database={database_name};
    UID=;
    PWD=;
                      """)


def sku_search():

    SKU_check = '''SELECT [ITEMSKU] FROM
    [StilettoXT].[dbo].[PRODDETAIL] WHERE
    ITEMSKU = (?)'''
    SKU_code = input('Please enter the SKU code: ')
    cursor = conn.cursor()
    cursor.execute(SKU_check, SKU_code)
    if cursor.fetchall() == []:
        print('Not Found')
    elif cursor.fetchall() != []:
        print('Found')


sku_search()

conn.close()

I'm having real difficulty trying to get the following code to work, specially the 'elif' part of the my if statement. If you run the script with an invalid SKU code that doesn't exists in that database, you get the print statement. If you run with a valid SKU code, nothing gets returned even though the cursor.fetchall() is not an empty list. If you swap the if and elif arguments round, you will only get a result for the 'if' part of the function. I can't understand why the 'elif' part returns nothing. If you query an invalid sku code, SQL will return a blank value. I've tried to reference this as None as well but the same issue. Any suggestions would be greatly appreciated!

Aucun commentaire:

Enregistrer un commentaire