Home > database >  Python SQL Query output with psycopg2
Python SQL Query output with psycopg2

Time:10-27

I've sucessfully done a Select query on Python using psycopg2, but i have a problem with the output.

The output is as follows:

[('Porto',), ('Milan',), ('London',)]

The problem is when i try to pass it as a variable on an API string

cityList = records

for city in cityList:
    api = f"https://api.example.io/?city={city}"

I get an API error because the input it's been read as:

https://api.example.io/?city=('Porto',)

I know it's because it's a string, but how to i pass it to the API as a variable in a way that i can loop through the DB results as:

https://api.example.io/?city=Porto

Thank you for any help.

CodePudding user response:

You have a list of rows where each element is a tuple containing all the columns retrieved for each row, which in your case contains a single element. So what you should do instead is chose the one and only column from each row:

cityList = records

for city in cityList:
    api = f"https://api.example.io/?city={city[0]}"

What you were doing was converting the entire tuple to a string instead of the first and only element within the tuple.

  • Related