eclipse 属性错误:模块'odbc'没有属性'connect' - python与pydev

6ljaweal  于 2022-11-04  发布在  Eclipse
关注(0)|答案(4)|浏览(176)

我对python很陌生,我似乎找不到这个错误的答案。当我运行下面的代码时,我得到了这个错误

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

但是,这个错误只在eclipse中出现。如果我通过命令行运行它就没有问题了。我运行的是python 3.5。我做错了什么?

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')

删除try...except块的建议对我不起作用。现在实际导入抛出如下错误:

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

我确实安装了pyodbc,导入和连接在windows上的命令行中工作正常。
谢谢你

bvjveswy

bvjveswy1#

这里的问题是pyodbc模块没有导入到您的try/except块中。我强烈建议不要将import语句放在try块中。首先,您需要确保您已经安装了pyodbcpip install pyodbc),最好是安装在virtualenv中,然后您可以这样做:

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)

如果你在Windows上运行(如果有DRIVER=参数的话,看起来是这样的),看看virtualenvwrapper-win如何管理Windows Python虚拟环境:https://pypi.python.org/pypi/virtualenvwrapper-win
祝你好运!

r7s23pms

r7s23pms2#

Flipper的回答帮助确定了问题是在eclipse的外部库列表中引用了一个不正确的库。在修复它之后,问题得到了解决。

fae0ux8s

fae0ux8s3#

python文件的名称是什么?如果你不小心将其命名为'pyodbc.py',你会得到这个错误。因为它试图导入自己而不是预期的pyodbc模块。

2j4z5cfb

2j4z5cfb4#

这里是解决方案!简单地安装和使用'pypyodbc'而不是'pyodbc'!我有我的测试例子如下。更改您的数据为SERVER_NAME和DATA_NAME和DRIVER。也把您自己的记录。祝你好运!

import sys
import pypyodbc as odbc

records = [
    ['x', 'Movie', '2020-01-09', 2020],
    ['y', 'TV Show', None, 2019]
]

DRIVER = 'ODBC Driver 11 for SQL Server'
SERVER_NAME = '(LocalDB)\MSSQLLocalDB'
DATABASE_NAME = 'D:\ASPNET\SHOJA.IR\SHOJA.IR\APP_DATA\DATABASE3.MDF'

conn_string = f"""
    Driver={{{DRIVER}}};
    Server={SERVER_NAME};
    Database={DATABASE_NAME};
    Trust_Connection=yes;
"""

try:
    conn = odbc.connect(conn_string)
except Exception as e:
    print(e)
    print('task is terminated')
    sys.exit()
else:
    cursor = conn.cursor()

insert_statement = """
    INSERT INTO NetflixMovies
    VALUES (?, ?, ?, ?)
"""

try:
    for record in records:
        print(record)
        cursor.execute(insert_statement, record)
except Exception as e:
    cursor.rollback()
    print(e.value)
    print('transaction rolled back')
else:
    print('records inserted successfully')
    cursor.commit()
    cursor.close()
finally:
    if conn.connected == 1:
        print('connection closed')
        conn.close()

相关问题