Gere
Gere

Reputation: 12697

SQLAlchemy import errors in Pydev/Eclipse

I tried installing SQLAlchemy for Python 3.2 which I use with Eclipse/Pydev. A simple test script fails

from sqlalchemy.engine import create_engine
engine=create_engine("mysql://user:password@server/database")

If I run it from Eclipse I get

Traceback (most recent call last):
  File "...\sqlalchemy.py", line 1, in <module>
    from sqlalchemy.engine import create_engine
  File "...\sqlalchemy.py", line 1, in <module>
    from sqlalchemy.engine import create_engine
ImportError: No module named engine

However I actually generated the import line with Ctrl-Shirt-O, so Eclipse found that automatically and knows about it. Also Pydev does not show any errors in the script.

If I try the same script in the interactive Pydev console I get

from sqlalchemy.engine import create_engine
engine=create_engine("mysql://user:password@server/database")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python32\lib\site-packages\sqlalchemy-0.7.8-py3.2.egg\sqlalchemy\engine \__init__.py", line 338, in create_engine
    return strategy.create(*args, **kwargs)
  File "C:\Python32\lib\site-packages\sqlalchemy-0.7.8-py3.2.egg\sqlalchemy\engine\strategies.py", line 64, in create
    dbapi = dialect_cls.dbapi(**dbapi_args)
  File "C:\Python32\lib\site-packages\sqlalchemy-0.7.8-py3.2.egg\sqlalchemy\connectors\mysqldb.py", line 52, in dbapi
    return __import__('MySQLdb')
ImportError: No module named MySQLdb

Do you have an idea how to get it work?

Upvotes: 2

Views: 3294

Answers (2)

Answer is simple: your main module is named sqlalchemy.py. This is a trap that was much more easier to fall in python 2 - naming your own module by the same name as a system module.

At startup your sqlalchemy.py is loaded by python as the __main__ module, and when the first line runs, python reloads sqlalchemy.py as the module sqlalchemy; the second time the import line is run the python interpreter already finds sqlalchemy in sys.modules, but it does not contain the variable or module named engine.

For easy fix rename sqlalchemy.py to for example satest.py. For more complete solution, organize your code in packages.

Upvotes: 4

Gere
Gere

Reputation: 12697

While the first error was an unfortunate mistake as explained by Antti I finally also solved the other issue. I didn't have MySQLdb installed which again requires a MySQL Server. Instead I have mysql-connector for which the correct syntax is

engine=create_engine("mysql+mysqlconnector://...")

I didn't see this while looking for quick test examples.

Upvotes: 1

Related Questions