Search code examples
pythoneclipsepydevpyodbc

AttributeError: module 'odbc' has no attribute 'connect' - python with pydev


I am very new to python and I just can't seem to find an answer to this error. When I run the code below I get the error

AttributeError: module 'odbc' has no attribute 'connect'

However, the error only shows in eclipse. There's no problem if I run it via command line. I am running python 3.5. What am I doing wrong?

try:
    import pyodbc
except ImportError:
    import odbc as pyodbc

# Specifying the ODBC driver, server name, database, etc. directly
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=PXLstr,17;DATABASE=Dept_MR;UID=guest;PWD=password')

The suggestion to remove the try...except block did not work for me. Now the actual import is throwing the error as below:

Traceback (most recent call last):
  File "C:\Users\a\workspace\TestPyProject\src\helloworld.py", line 2, in <module>
    import pyodbc
  File "C:\Users\a\AppData\Local\Continuum\Anaconda3\Lib\site-packages\sqlalchemy\dialects\mssql\pyodbc.py", line 105, in <module>
    from .base import MSExecutionContext, MSDialect, VARBINARY

I do have pyodbc installed and the import and connect works fine with the command line on windows.

thank you


Solution

  • The problem here is that the pyodbc module is not importing in your try / except block. I would highly recommend not putting import statements in try blocks. First, you would want to make sure you have pyodbc installed (pip install pyodbc), preferably in a virtualenv, then you can do something like this:

    import pyodbc
    
    cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=PXLstr,17;DATABASE=Dept_MR;UID=guest;PWD=password')
    
    cursor = cnxn.cursor()
    cursor.execute('SELECT 1')
    
    for row in cursor.fetchall():
        print(row)
    

    If you're running on Windows (it appears so, given the DRIVER= parameter), take a look at virtualenvwrapper-win for managing Windows Python virtual environments: https://pypi.python.org/pypi/virtualenvwrapper-win

    Good luck!