Kade Williams
Kade Williams

Reputation: 1181

Only display available results from PyODBC

I'm am querying a database and displaying the name or result. If there are several "Michael" names in the database, all names with their last name are displayed.

If there is only 1 Michael in the database, that Michael's full name is displayed along with an error "List index out of range."

This is because I am asking the program to display 4 results with the name Michael but there is only one available.

How do I fix this when using

        for _ in range(0, 4):
            print(str(results[_])) # displays results

Here is everything:

import pypyodbc

def queryfirst():
    return ("SELECT FIRSTNAME, LASTNAME "      
            "FROM dbo.My_Table "
            "WHERE FIRSTNAME = ?")

def sqlfirst():
    firstname = "Michael"
    if True:    
        connection = pypyodbc.connect('Driver={SQL Server};Server=mysSQLserver;Database=MyDatabaseName;Trusted_Connection=yes;')
        cursor = connection.cursor() 
        SQLCommand = queryfirst()
        Values = [firstname]
        cursor.execute(SQLCommand,Values)
        return cursor.fetchmany(4)


def calculate():
    results = sqlfirst()
    if results:
        for _ in range(0, 4):
            print(str(results[_])) # enters results in entry
        connection.close()


calculate()

I'm not sure how I can say "If results are less than 4, only display results available." Does cursor.fetchmany or cursor.fetchall make a difference?

Do I need to get the length of results?

Upvotes: 1

Views: 36

Answers (1)

fralau
fralau

Reputation: 3839

At first glance, it's not a matter of SQL interface, but basic mechanics of Python.

You should be using the basic for construct:

def calculate():
    results = sqlfirst()
    for r in results:
        print(str(r))

In practice it will take care of the cases where you have 4, 1, or 0.

P.S. Unless you intend to parameterize your query at a later stage, you might want to use a variable and since it's a "constant":

QUERY_FIRST = "SELECT FIRSTNAME, LASTNAME"      
             "FROM dbo.My_Table"
             "WHERE FIRSTNAME = ?"

Upvotes: 1

Related Questions