Search code examples
pythonsqlpostgresqldbeaver

When executing an SQL query using session.execute(sql_to_string()) I get AttributeError: 'str' object has no attribute 'as_string'


When I run the below:

# 'session' points to a databse    

t = tuple(a_list_of_ids)
query = "select val from sval where id IN {}".format(t)

ids_to_delete = session.execute(sql_to_string(session, query))

I get the following error:

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/some_path/find_and_delete_ICE_contracts_non_tradeable_first_alive.py", line 34, in find_ice_contracts_on_dte
    is_tradeable_values_of_ids_to_soft_delete = session.execute(sql_to_string(session, query))
  File "some_path/util/sql_translation.py", line 621, in sql_to_string
    return stmt.as_string(psycopg2_connection)
AttributeError: 'str' object has no attribute 'as_string'

Any ideas how to format the above so that it works?

I also tried session.execute without the sql_to_string, but that doesn't work either.


Solution

  • # Convert the list to ids string
    a_list_of_ids = [1, 2, 3]  # Example list of IDs
    id_string = ', '.join(str(id) for id in a_list_of_ids)
    
    # Make Query Here (notice the id_string is wrapped in brackets
    query = "SELECT val FROM sval WHERE id IN ({})".format(id_string)
    
    # Then Execute
    result = session.execute(query)