Psycopg2: 'module' object has no attribute 'connect'

风流意气都作罢 提交于 2019-12-11 02:23:51

问题


I'm trying to connect to a postgres database with psycopg2:

import psycopg2

try:
    conn = psycopg2.connect("dbname='puppetdb' user='puppetdb' host='172.17.0.1' port='5432' password='puppetdb'")
except Exception, e:
    print "I am unable to connect to the database"
    print e

Which returns:

I am unable to connect to the database
'module' object has no attribute 'connect'

I've made sure that psycopg2 is installed with pip install psycopg2 and it seems like this should work according to the documentation.

Am I doing this wrong?


回答1:


This could be a name shadowing issue.

If your file is called psycopg2.py or if you have a psycopg2.py/psycopg2.pyc file in that directory then it will import your script over the actual pyscopg2 module.

If that's the issue then rename your file to something else.




回答2:


For me it was because I was uploading a zip to AWS lambda and wasn't zipping the folder recursively, i.e. zip lambda.zip * instead of zip -r lambda.zip *. So the module folder was empty.




回答3:


import psycopg2               # Acc�s PostgreSQL
import psycopg2.extras        # Goodies PostgreSQL

try:
     conn = psycopg2.connect("dbname='puppetdb' user='puppetdb' 
host='172.17.0.1' port='5432' password='puppetdb'")

except psycopg2.Error as e:
    print("I am unable to connect to the database")
    print(e)


来源:https://stackoverflow.com/questions/43767658/psycopg2-module-object-has-no-attribute-connect

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!