0

I am trying to see if I already have an item in the database. However I can't figure out how to select the name with an apostrophe(') in them.

I have tried using adapt, %s (which does not work at all). :item syntax does not work either.

The below select will result in

Exception has occurred: ProgrammingError
(psycopg2.errors.SyntaxError) syntax error at or near "s"
LINE 1: select * from items where name = 'Akunda's Bite'

# CODE
str_sql = text(f"select * from items where name = '{item_name}'")

results = self.conn.execute(str_sql).fetchone()
0

1 Answer 1

2

Rather than using (f-) string formatting, use the DB-API's parameter substitution method:

str_sql = text("select * from items where name = %s;")
results = self.conn.execute(str_sql, (item_name,)).fetchone()

Note that the value(s) must be passed as a sequence; specifically a tuple or a list. A string is a sequence, but each character in the string will be interpreted as a distinct value for the query, which will result in

TypeError: not all arguments converted during string formatting

being raised.

Sign up to request clarification or add additional context in comments.

2 Comments

This does not need a tuple. str_sql = "select * from items where name = %s" results = self.conn.execute(str_sql, item_name).fetchone()
Then item_name must be a tuple or list.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.