Dyl10
Dyl10

Reputation: 161

I'm receiving the error 'except MySQLdb.error, e' Syntax Error - invalid syntax when trying to write my scrapy spider to mysql,

Here is my pipelines.py and I'm receiving an error on line 18.

import sys;sys.path.append("/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages")
import MySQLdb
import hashlib
from scrapy.exceptions import DropItem
from scrapy.http import Request

class TestPipeline(object):

    def __init__(self):
        self.conn = MySQLdb.connect(user='test', passwd='password', db='c1024403', host='ephesus.cs.cf.ac.uk', charset='utf8', use_unicode=True)
        self.cursor = self.conn.cursor()

    def process_item(self, item, spider):
        try:
            self.cursor.execute("""INSERT INTO test (test1, test2) VALUES (%s, %s)""", (item['Country'], item['Qualification']))
            self.conn.commit()

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

        return item

Heres the error -

File "project\pipelines.py", line 18
except MySQLdb.Error, e:
     ^
SyntaxError: invalid syntax

I've installed mysql-python and visual c++ 2008 express, I don't understand what the error means as I can't find anything about it anywhere else on the internet.

Upvotes: 1

Views: 5563

Answers (1)

Omid Raha
Omid Raha

Reputation: 10680

You are running your code with Python 3.x, but your code scheme for try.. except section is for Python 2.X.

If you want to run your code with Python 3.x, then change this line:

except MySQLdb.Error, e:

To:

except MySQLdb.Error as e:

And if you want this section of code works with Python 2.x and also Python 3.x, then change it to:

except MySQLdb.Error:
    e = sys.exc_info()[1]

Read more.

But according to your print statement, you write your script for Python 2.x, so it's better to run your code with Python 2.x, instead of Python 3.x

Also this sys.path.append("../python2.7/site-packages") line is strange in first line of your script.

Also your indention of your first code that you pasted was wrong, and i think your are still using that, please use current edited version that is now in your question.

Upvotes: 7

Related Questions