0

how to format the string to insert it into a table in postgresql? example I have the sql:

req="INSERT INTO table_a values('%s','%s','%s','%s')"

and the values

values=["Socit d'Invest Variable", '6465', 'hg', 'fk_id']
cursor.execute(req,tuple(values))

I get the error :

psycopg2.ProgrammingError: syntax error at or near "Socit"
LINE 1: ...column0, column1, column2, column3) Values (''Socit d'Invest...

any Idea how to change the string from using a single quote ' to a double quote " ?

2
  • What version of psycopg2 are you using? It should automatically escape it for you. Have a look at the example from the docs: initd.org/psycopg/docs/… Commented Mar 30, 2015 at 10:00
  • it's an error in the quote when formating string look at the answer Commented Mar 30, 2015 at 10:06

2 Answers 2

2

the error was in the req

req="INSERT INTO table_a values('%s','%s','%s','%s')"

must be without quote '

req="INSERT INTO table_a values(%s,%s,%s,%s)"
Sign up to request clarification or add additional context in comments.

Comments

0

I think you need to use backslash to escape your singlequote in the string for executing query correctly, so either use:

values = ['Socit d\'Invest Variable', '6465', 'hg', 'fk_id']

or

values = ["Socit d\'Invest Variable", '6465', 'hg', 'fk_id']

should be working

2 Comments

@m3asmi How about use req="INSERT INTO table_a values(%s,%s,%s,%s)" ?
@m3asmi Nice! I should have noticed that earlier :p

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.