PostgreSQL- ModuleNotFoundError:没有名为“ psycopg2”的模块

时间:2019-04-19 00:08:49

标签: python python-3.x psycopg2 postgresql-9.1

我可以确认psycopg2已安装(使用conda install -c anaconda psycopg2),但似乎无法将psycopg2导入到我的python脚本中,或者解释器无法找到它。我还尝试使用pip3进行安装,满足要求,这意味着已经安装了psycopg2,但无法理解为什么我的脚本无法导入。使用Mac(OS v10.14.4)

$ python create_tables.py
Traceback (most recent call last):
  File "create_tables.py", line 1, in <module>
    import psycopg2
ModuleNotFoundError: No module named 'psycopg2'

$ pip3 install psycopg2
Requirement already satisfied: psycopg2 in /usr/local/lib/python3.7/site-packages (2.8.2)
$ pip3 install psycopg2-binary
Requirement already satisfied: psycopg2-binary in /usr/local/lib/python3.7/site-packages (2.8.2)
python -V
Python 3.7.0

知道为什么会这样吗?

编辑:create_table.py

import psycopg2
from config import config


def create_tables():
    """ create tables in the PostgreSQL database"""
    commands = (
        """
        CREATE TABLE vendors (
            vendor_id SERIAL PRIMARY KEY,
            vendor_name VARCHAR(255) NOT NULL
        )
        """,
        """ CREATE TABLE parts (
                part_id SERIAL PRIMARY KEY,
                part_name VARCHAR(255) NOT NULL
                )
        """,
        """
        CREATE TABLE part_drawings (
                part_id INTEGER PRIMARY KEY,
                file_extension VARCHAR(5) NOT NULL,
                drawing_data BYTEA NOT NULL,
                FOREIGN KEY (part_id)
                REFERENCES parts (part_id)
                ON UPDATE CASCADE ON DELETE CASCADE
        )
        """,
        """
        CREATE TABLE vendor_parts (
                vendor_id INTEGER NOT NULL,
                part_id INTEGER NOT NULL,
                PRIMARY KEY (vendor_id , part_id),
                FOREIGN KEY (vendor_id)
                    REFERENCES vendors (vendor_id)
                    ON UPDATE CASCADE ON DELETE CASCADE,
                FOREIGN KEY (part_id)
                    REFERENCES parts (part_id)
                    ON UPDATE CASCADE ON DELETE CASCADE
        )
        """)
    conn = None
    try:
        # read the connection parameters
        params = config()
        # connect to the PostgreSQL server
        conn = psycopg2.connect(**params)
        cur = conn.cursor()
        # create table one by one
        for command in commands:
            cur.execute(command)
        # close communication with the PostgreSQL database server
        cur.close()
        # commit the changes
        conn.commit()
    except (Exception, psycopg2.DatabaseError) as error:
        print(error)
    finally:
        if conn is not None:
            conn.close()


if __name__ == '__main__':
    create_tables()

2 个答案:

答案 0 :(得分:1)

是,找到了解决方案 python -m pip install psycopg2-binary可以解决问题!

答案 1 :(得分:0)

我假设python指向python2,但是由于您正在使用python3,因此您为pip3安装了psycopg2。通过pip install pyscopg2 psycopg2-binary进行安装,其中点应指向python2