0

I am new to python and just been playing with the database API. I am getting an invalid syntax error in the exception except block comma. I can't figure out any syntax mistakes. Below is the code I am using

import time
import MySQLdb
import sys
import urllib2

#f = open("../", 'r')

try: 
    db = MySQLdb.connect(host="localhost", user="test", passwd="test",db="test")
    cur = db.cursor()

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

finally:
    cur.close()
    db.close()
#f.write('amal')
#f.close()
5
  • 2
    Are you trying to run this with Python 3 perhaps? You are using Python 2 libraries here, so even if you were to correct the syntax it won't work. Commented Mar 13, 2014 at 13:04
  • Also, including the traceback makes it much easier for us to help you :) Commented Mar 13, 2014 at 13:06
  • Try except MySQLdb.Error as e:. Commented Mar 13, 2014 at 13:06
  • Thanks for the quick reply Martijn Pieters.. Yes, i am using Python 3.. Commented Mar 13, 2014 at 13:07
  • Andrei Horak ... Thanks... Let me try it... Commented Mar 13, 2014 at 13:09

1 Answer 1

5

Your syntax is correct for Python 2, which would be the correct version given the fact that you tried to import urllib2 here.

For recent Python versions the except syntax was updated, and the old syntax no longer works in Python 3. The correct syntax would be:

except MySQLdb.Error as e:

but you'll need to fix what Python version you are running this with or use the correct libraries for Python 3. That means using urllib.request and installing MySQLdb for your Python 3 installation first.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.