1

I am trying to test the following with python but I get the invalid syntax error:

db = None

try:

db = mdb.connect("localhost","user","pass","dbName") 

with db:

    cur = db.cursor()                   
    cur.execute("SELECT * from product")

    rows = cur.fetchall()
    for row in rows:
        print row

except mdb.Error, e:

print "Error %d: %s" % (e.args[0],e.args[1])
sys.exit(1)

The error is the following:

  File "script.py", line 11
with db:
      ^
SyntaxError: invalid syntax

How do I fix this?

5
  • Can you please include the SyntaxError and format the first couple of lines of your code exactly as you have them in your script? Commented Feb 24, 2013 at 3:04
  • Please reformat your question. Commented Feb 24, 2013 at 3:08
  • Except for the indentation everthing seems to be ok. Are you sure that you are using python 2.7? Commented Feb 24, 2013 at 3:34
  • actually not. I am using python 2.4 apparently Commented Feb 24, 2013 at 3:43
  • Well the with statement is available from python 2.5+. That's pretty much why it will never work. python.org/dev/peps/pep-0343 Commented Feb 24, 2013 at 3:58

1 Answer 1

2

I'd be nice to see all your imports declarations too to see what could be missing from your code. I assume that you at least have the import MySQLdb somewhere. I made a dummy database with a couple of data rows to test this out. Not sure how python let you get away with the indentation blocks being all messed up, but maybe it's just your code indentation posting error on here.

This is the code I tried and seemed to have no issues:

import MySQLdb as mdb

db = None

try:

    db = mdb.connect("localhost","user", "password", "test_data")

    ## with db:  ## try taking this out for Python 2.4
    cur = db.cursor()
    cur.execute("SELECT * FROM PRODUCT")
    rows = cur.fetchall()
    for row in rows:
        print row

except mdb.Error, e:

    print "Error %d: %s" % (e.args[0],e.args[1])
    sys.exit(1)
Sign up to request clarification or add additional context in comments.

1 Comment

Just saw your last comment. If you are using Python 2.4, try taking out the "with db:" line.

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.