1

I have a query which works well in psql, but generates an error in my program:

sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
cur.execute(sql)

Any pointers as to why it's not working? Or any suggestions, how I can fix it?

ZygD
24.8k41 gold badges107 silver badges145 bronze badges
asked Mar 30, 2015 at 21:40

2 Answers 2

5

It is not about PostgreSQL vs MySQL query syntax - this is just syntactically wrong in Python:

>>> sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
 File "<stdin>", line 1
 sql = 'SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;' 
 ^
SyntaxError: invalid syntax

Put the query into double quotes:

sql = "SELECT id, x, y FROM table_name WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;"
answered Mar 30, 2015 at 21:43
Sign up to request clarification or add additional context in comments.

1 Comment

I feel silly now, totally never thought of it. thanks.
0

The good practice for code strings in Python is the triple quoted string which makes it much clearer and can contain both single and double quotes:

sql = '''
 SELECT id, x, y
 FROM table_name
 WHERE y NOT LIKE 'pa%' AND x IS NOT NULL;
'''

From the manual:

Triple quoted strings may span multiple lines - all associated whitespace will be included in the string literal.

answered Feb 17, 2016 at 17:30

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.