import psycopg db = psycopg.connect('dbname=test') c = db.cursor() str = "hel'lo" c.execute("select %(text)s where %(text)s <> ''", { 'text': str}) db.commit() for i in c.fetchall(): print i c.execute("select %(text)s where %(text)s <> ''", { 'text': psycopg.Binary(str)}) db.commit() for i in c.fetchall(): print i