1

I am having a field called comments. I am effectively trying to read values from one large table into multiple tables. Hence, my select query fetches the comment field for me.

I am constructing a Python script to do the copying from table to table. My insert query fails when it encounters a comment field like "Sorry! we can't process your order" because of the single quote.

I have tried using $ quotes but in vain

Here is what I am trying

#!/usr/bin/python

import psycopg2

conn = psycopg2.connect("dbname='postgres' user='postgres' host='localhost' )
mark=conn.cursor()
/* fectching the rows and doing other stuff */

addthis="insert into my_table(something) values("$$"+str(row[8])+"$$")
mark.execute(addthis)
conn.commit()

Appreciate the help!

3
  • 2
    You need to find a new database tutorial, as your current one is failing you badly. Commented Apr 14, 2012 at 5:07
  • Ignacio Vazquez-Abrams: I have no option! Do u have any other workarounds? Commented Apr 14, 2012 at 5:11
  • 5
    Yes. Use DB-API 2 as it's meant to be used. See a tutorial. Commented Apr 14, 2012 at 5:13

2 Answers 2

6
  1. Your insert statement should use a placeholder. In the case of psycopg2, it is %s.
  2. You should pass the parameter(s) as a second argument to execute(). That way you don't have quoting issues and you guard against SQL-injection attack.

For example:

addthis = "INSERT INTO my_table (something) VALUES (%s);"
mark.execute(addthis, ('a string you wish to insert',))
Sign up to request clarification or add additional context in comments.

Comments

-3

You could use a placeholder, as suggested by bernie. This is the preferred way.
There are however situations where using a placeholder is not possible. You then have to escape the qoutes manually. This is done by backslashing them:

addthis="insert into my_table(something) values(%s)" % str(row[8]).replace('"', r'\"').replace("'", r"\'")
mark.execute(addthis)

1 Comment

No - he should use a placeholder. If you're asking questions like this, then the last thing you should do is start putting together your own ad-hoc escaping. Yours doesn't work anyway.

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.