1

I am new to working on Python. I m not able to understand how can I send the correct input t0 the query.

      list_of_names = []

    for country in country_name_list.keys():
        list_of_names.append(getValueMethod(country))

    sql_query = f"""SELECT *  FROM table1
                            where name in (%s);"""
                           

    db_results = engine.execute(sql_query, list_of_names).fetchone()

Give the error " not all arguments converted during string formatting"
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
Tanu
  • 1,286
  • 4
  • 16
  • 35
  • 1
    The query only has one placeholder `%s`, therefore it expects `list_of_names` to only have one name. But it had more than that. – John Gordon Feb 17 '23 at 05:33

2 Answers2

0

As implied by John Gordon's comment, the number of placeholders in the SQL statement should match the number of elements in the list. However SQLAlchemy 2.0+ no longer accepts raw SQL statements. A future-proof version of the code would be:

import sqlalchemy as sa
...

# SQL statements should be wrapped with text(), and should used
# the "named" parameter style.
sql_query = sa.text("""SELECT * FROM table1 where name in :names)"""

# Values should be dictionaries of lists of dictionaries,
values = {'names': list_of_names}

# Execute statements using a context manager.                       
with engine.connect() as conn:
    db_results = conn.execute(sql_query, values).fetchone()
snakecharmerb
  • 47,570
  • 11
  • 100
  • 153
-2

If I know right, there are a simpler solution. If you write curly bracets {}, not bracets (), and you place inside the bracets a variable, which contains the %s value, should work. I don't know, how sql works, but you should use one " each side, not three.

Sorry, I'm not english. From this, maybe I wasn't help with the question, because I don't understand correctly.

Charles
  • 7
  • 3
  • String formatting techniques to inject values into SQL statements is error-prone and insecure - use parameter [substitution instead](https://stackoverflow.com/questions/902408/how-to-use-variables-in-sql-statement-in-python). [Triple-quoted strings](https://docs.python.org/3/glossary.html?highlight=triple#term-triple-quoted-string) are legal Python syntax. – snakecharmerb Feb 17 '23 at 07:43