17

I am trying to print the results of my query to the console, with the below code, but it keeps returning me the object location instead.

test = connection.execute('SELECT EXISTS(SELECT 1 FROM "my_table" WHERE Code = 08001)')
print(test)

Result that I get is - <sqlalchemy.engine.result.ResultProxy object at 0x000002108508B278>

How do I print out the value instead of the object?

Reason I am asking is because I want to use the value to do comparison tests. EG:

if each_item not in test:
    # do stuffs
Dharman
  • 30,962
  • 25
  • 85
  • 135
jake wong
  • 4,909
  • 12
  • 42
  • 85

2 Answers2

18

Like this, test contains all the rows returned by your query.

If you want something you can iterate over, you can use fetchall for example. Like this:

test = connection.execute('SELECT EXISTS(SELECT 1 FROM "my_table" WHERE Code = 08001)').fetchall()

Then you can iterate over a list of rows. Each row will contain all the fields. In your example you can access fields by their position. You only have one at position one. So that's how you can access 1:

for row in test:
    print(row[0])
sandor
  • 643
  • 6
  • 16
  • Hmm, This returns me `0`. Not sure why – jake wong Feb 07 '17 at 16:22
  • Okay. I think I know why. it is stored in SQL as a `string` so, that is the reason why it returned `0` :) – jake wong Feb 07 '17 at 16:24
  • It makes sense, if it would be a number you wouldn't have a leading zero. When i reproduced the issue, I used a `number`, not a `string`. – sandor Feb 07 '17 at 16:28
  • What if there's no returned rows? Like in a `BEGIN/END` clause? `sqlalchemy.exc.ResourceClosedError: This result object does not return rows. It has been closed automatically.` – alex Sep 30 '22 at 19:56
1

test is an object containing the rows values. So if the column's name is value, you can call it using test.value.

If you're looking for more "convenient" way of doing so (like iterating through each column of test), you'd have to explicitly define these functions (either as methods of test or as other functions designed to iterate through those types of rows).