ahinkle
ahinkle

Reputation: 2261

Python Array Extra Comma Formatting

I'm pretty new to Python and I have done some research on this question but I can't seem to find an answer.

I have a select query that sends to an array (Python 2.7)

query = "SELECT catalog_product_entity.sku "
query = query+"FROM catalog_product_entity "
query = query+"INNER JOIN catalog_product_entity_decimal "
query = query+"ON catalog_product_entity_decimal.entity_id = catalog_product_entity.entity_id "
query = query+"INNER JOIN catalog_product_entity_int "
query = query+"ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id "
query = query+"WHERE catalog_product_entity.sku IS NOT NULL "
query = query+"AND catalog_product_entity_int.attribute_id = '84'"
x = myconn.cursor()
x.execute(query)
skuArray = x.fetchall()
for i in skuArray:
    print i

The query works sucessfully but displays as: ('000381001238',),

How can I format the array to display as ('000381001238'),?

I have also tried this:

for i in skuArray:
    prodSku = [i[0] for  in x.fetchall()]
    print prodSku 

Side note for performance, This query has over 8000 unique values.

Upvotes: 1

Views: 61

Answers (2)

alecxe
alecxe

Reputation: 473893

fetchall() returns a list of rows which, if a default cursor is used, are represented by tuples. If you have a single column in the select statement, simply get it by index:

for row in x.fetchall():
    print(row[0])

Or, if you need to collect the column values in a list:

sku_values = [row[0] for row in x.fetchall()]

As a side note, you don't have to concatenate parts of the query with += - you can use Python's multiline strings where, as a bonus, you'll be able to indent your query properly that will improve readability:

query = """
    SELECT catalog_product_entity.sku
    FROM catalog_product_entity
        INNER JOIN catalog_product_entity_decimal ON catalog_product_entity_decimal.entity_id = catalog_product_entity.entity_id
            INNER JOIN catalog_product_entity_int ON catalog_product_entity_int.entity_id = catalog_product_entity.entity_id 
    WHERE catalog_product_entity.sku IS NOT NULL 
          AND catalog_product_entity_int.attribute_id = '84'
"""

Upvotes: 3

Daniel Lee
Daniel Lee

Reputation: 8021

It looks like fetchall() is returning a tuple:

try:

for i in skuArray:
    print i[0]

to only get the first element of the tuple.

Upvotes: 3

Related Questions