PostgreSQL- ModuleNotFoundError: No module named 'psycopg2' - python

I can confirm psycopg2 is install (using conda install -c anaconda psycopg2) but the it seems psycopg2 cannot be imported to my python script or the interpreter is unable to locate it. I also tried installing using pip3, requirements are satisfied, meaning psycopg2 is already istalled, but cannot understand why I script isn't able to import it. Using 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
Any idea why this happen?
EDIT: 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()

Yes, found a solution,
python -m pip install psycopg2-binary
does the trick!

Using Python3 the command is:
python3 -m pip install psycopg2-binary

I assume python points to python2, but you installed psycopg2 for python3 since you are using pip3. Install it via pip install pyscopg2 psycopg2-binary where pip should point to python2

Related

how to move from sqllite database to mysql database?

i want to move from SQLite database M, MySQL database. if i understood correctly, so i can do it with changing the engine:
engine = create_engine('sqlite:///foo.db', echo = False)
to:
engine = create_engine('mysql://username:password#localhost/ db_name (the database name) ')
engine = create_engine("mysql+pymysql://user:pass#some_mariadb/dbname?charset=utf8mb4")
or
engine = create_engine("mariadb+pymysql://user:pass#some_mariadb/dbname?charset=utf8mb4")
sqlalchemy-mysql
pip install MySQL-python
On Ubuntu based systems:
apt-get install python-mysqldb
On RHEL/CentOS based systems:
yum install MySQL-python
On Windows:
Unofficial Windows Binaries for Python Extension Packages

psycopg2 - ImportError: DLL load failed while importing _psycopg: The operating system cannot run %1

I installed psycopg2 using conda on Windows 10.
https://anaconda.org/anaconda/psycopg2
I did it in a clean new conda environment (named wr).
I then tried to run this sample app but I am getting this error (see below).
I have no idea what I might be doing wrong because it was all straightforward and I did it in a clean way.
Any ideas how to solve this?
import psycopg2
try:
connection = psycopg2.connect(user = "***",
password = "***",
host = "***",
port = "5432",
database = "***")
cursor = connection.cursor()
# Print PostgreSQL Connection properties
print ( connection.get_dsn_parameters(),"\n")
# Print PostgreSQL version
cursor.execute("SELECT version();")
record = cursor.fetchone()
print("You are connected to - ", record,"\n")
except (Exception, psycopg2.Error) as error :
print ("Error while connecting to PostgreSQL", error)
finally:
#closing database connection.
if(connection):
cursor.close()
connection.close()
print("PostgreSQL connection is closed")
Error in VS code:
PS C:\Work\WRR\git\tools\JTunnelTestApp> cd 'c:\Work\WRR\git\tools\JTunnelTestApp'; & 'C:\Programs\Anaconda3\envs\wr\python.exe' 'c:\Users\petrop01\.vscode\extensions\ms-python.python-2020.9.114305\pythonFiles\lib\python\debugpy\launcher' '56143' '--' 'c:\Work\WRR\git\tools\JTunnelTestApp\main.py'
Traceback (most recent call last):
File "c:\Work\WRR\git\tools\JTunnelTestApp\main.py", line 1, in <module>
import psycopg2
File "C:\Programs\Anaconda3\envs\wr\lib\site-packages\psycopg2\__init__.py", line 51, in <module>
from psycopg2._psycopg import ( # noqa
ImportError: DLL load failed while importing _psycopg: The operating system cannot run %1.
PS C:\Work\WRR\git\tools\JTunnelTestApp>
EDIT: Seems they had a bug open for this 2 years ago and they just closed it, ignoring it completely.
https://github.com/psycopg/psycopg2/issues/734
you can use psycopg2-binary library instead of psycopg2. after installation the usage is the same.
For Windows when using Anaconda I have found that installing from the VS Code/Windows terminal just doesn't work for all cases. Instead install from the Anaconda terminal. I have no idea why this is the case, but it has been the fix on multiple computers.
Open Anaconda navigator
Environments
Select the environment you want to install psycopg2/psycopg2-binary to and Open Terminal
Uninstall any pervious installs
pip uninstall psycopg2
pip uninstall psycopg2-binary
Install again
pip install psycopg2
pip install psycopg2-binary
Now it should work.
Particularly found this useful to get standalone scripts that make use of Django ORM to work with Postgresql. Django was working fine, but without this fix the standalone scripts don't. Very strange.
for me updating to psycopg2 and psycopg2-binary to 2.8.6 worked in python 3.8
I found the solution in this reddit post, all credit to u/brianckeegan
If you're using conda to manage psycopg2 for Python 3.9+, the wheels point to an old version (v2.8.6) which causes this error. If you install via pip, you'll get a more up-to-date version (v2.9.1) that supports Python 3.9. Until the conda wheels are updated:
conda remove psycopg2
pip install psycopg2
For me, updating psycopg2 to 2.9.1 works in Python 3.10

How to use psycopg2-binary in Python?

I installed the psycopg2-binary package using pip install psycopg2-binary. But when how can I use it in Python?
import psycopg2 as pg2
conn = pg2.connect(database = 'dvdrental', user = 'postgres', password = secret)
cur = conn.cursor()
cur.execure('select * from actor')
cur.fetchmany(5)
---------------------------------------------------------------------------
ModuleNotFoundError Traceback (most recent call last)
<ipython-input-6-c2276cd20949> in <module>()
----> 1 import psycopg2 as pg2
2 conn = pg2.connect(database = 'dvdrental', user = 'postgres', password = secret)
3 cur = conn.cursor()
4 cur.execure('select * from actor')
5 cur.fetchmany(5)
ModuleNotFoundError: No module named 'psycopg2'
I'm using Django on a Mac. This is what worked for me.
In my virtual environment I ran:
pip install psycopg2-binary
In settings.py I specified:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
The database credentials have been left off. I understand this isn't what the OP was asking about, but hopefully it will be helpful to someone.
First install the dependencies,
sudo apt-get install build-dep python-psycopg2
And after that,
pip install psycopg2
Ubuntu/Debian
pg_config is usually installed by libpq-dev.
More details: https://www.psycopg.org/docs/install.html
Mac OS X
Try using Brew Package manager for macOS(or Linux)
https://brew.sh/
brew install postgresql
And if installed Postgres.app
Then update the PATH as
export PATH=$PATH:/Applications/Postgres.app/Contents/Versions/14/bin
Version can be checked via Applications->Postgres.app->Show Package Content->Contents->Versions->14
Afterwards do
pip install psycopg2

Django MySQL connection Error on windows Server

I have tried using
pip install mysqlclient and it says
Requirement already satisfied: mysqlclient in c:\program files\python37\lib\site-packages (1.3.12)
I have MySQL installed with the connector as well
but when i try to pip install MySQL-python
It Throws an error. it says Failed building Wheel for MySQL-python...
it also throws this exception
try:
import MySQLdb as Database
except ImportError as err:
raise ImproperlyConfigured(
'Error loading MySQLdb module.\n'
'Did you install mysqlclient?'
) from err
When i try to migrate the database, it doesnt migrate because it says mysql is not linked...
python37 doesn't support mysql yet.
Try this:
python3 -m pip install PyMySQL
Requirements
Python – one of the following:
CPython >= 2.7 or >= 3.4
Latest PyPy
MySQL Server – one of the following:
MySQL >= 5.5
MariaDB >= 5.5
https://pymysql.readthedocs.io/en/latest/user/installation.html

How to access the mysql database?

I am using python MySQL 5.7.19 on Ubuntu 16.04.1 and I am
trying to run the following code
import MySQLdb
db= MySQLdb.connect("localhost","root",YES,"testDB")
cursor=db.cursor()
cursor.execute("DROP TABLE IF EXISTS USER")
sql="""CREATE TABLE USER(
ID INT(12) NOT NULL AUTO_INCREMENT,
USERNAME VARCHAR(20) NOT NULL,
PASSWORD VARCHAR(20) NOT NULL,
PRIMARY KEY (ID)
)"""
cursor.execute(sql)
db.close()
When I save this in a .py file and execute it as Python3 I get the following error:
$ python3 try.py
Traceback (most recent call last):
File "try.py", line 1, in
import MySQLdb
ImportError: No module named 'MySQLdb'
How do I solve this?
install the package
pip install MySQL-python
or on Ubuntu
sudo apt-get install python-pip python-dev libmysqlclient-dev
Install the package using this command
sudo apt-get install python-mysqldb
and then use these thing to avoid non ascii character issue and persistent mysql db connection issue.
import MySQLdb
db = MySQLdb.connect("localhost", "root", "db_pswd", "mysql_db", charset='utf8', use_unicode=True)
db.ping(True)
use sudo apt-get install python-mysqldb don't specify python version, when system try to install, it will find the current python version in this system.

Categories