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
Related
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
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
I am trying to retrieve data from Kudu. But I am not able to install kudu-python package in anaconda or my server. Can I get some help with it? The documentation on the internet is not really clear.
#Karthik, did you encounter any errors? I just installed kudu-python client on Anaconda on Centos 6.9. There was one gotcha with versioning, but otherwise it was straightforward. The only error I ran into was
kudu/client.cpp:589:30: fatal error: kudu/util/int128.h: No such file or directory
there is a solution for it here: https://community.cloudera.com/t5/Data-Ingestion-Integration/can-not-install-kudu-python/td-p/67496
Otherwise, the steps are:
1. Install kudu client libraries as described on Kudu website (https://kudu.apache.org/docs/installation.html#_install_on_rhel_or_centos_hosts):
wget http://archive.cloudera.com/kudu/redhat/6/x86_64/kudu/cloudera-kudu.repo
sudo mv cloudera-kudu.repo /etc/yum.repos.d/
sudo yum update
sudo yum install kudu kudu-client0 kudu-client-devel
install a bunch of dev dependencies if you don't have them already:
sudo yum install autoconf automake libtool make gcc gcc-c++
install Cython and kudu-python
pip install Cython kudu-python==1.2.0
Once you have this installed, you can find examples in https://github.com/apache/kudu/tree/master/examples/python
i had no ability to install kudu-client (windows os is not supported) so i used the cluster's Impala to get Kudu's tables:
from impala.dbapi import connect
conn = connect('<Impala Daemon>', port=21050)
cursor = conn.cursor()
cursor.execute('SELECT * FROM mytable LIMIT 100')
print(cursor.description) # prints the result set's schema
results = cursor.fetchall()
https://github.com/cloudera/impyla
(windows server 2008 r2) python 34,
I changed settings.py:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'mydatabase',
'USER': 'mydatabaseuser',
'PASSWORD': 'mypassword',
'HOST': '127.0.0.1',
'PORT': '5432',
}
}
1) I run the command:
python manage.py migrate
i get an error:
error loading mysqldb module django.core.exception error loading mysqldb
2) I run the command:
pip install mysql -python
get "failed building wheel for mysql-python microsoft visulal c++ 2010 is required unable to find vcvarsall.bat
3) visual c++ 2010 was installed
I have in system variable path to:C:\Python34\Scripts;C:\Python34;
Furthermore i success to run commands from python to mysql (create\read\write table)
what else can i do in order the command python manage.py migrate will work?
You can use mysqlclient , it supports Python3 .You can read about it in django docs.
If
pip install MySQL-python
is failing, you can try easy_install MySQL-python.
Also install this: sudo apt-get install python-mysqldb
Solved by running the following command:
pip install mysqlclient
I'm trying to get the MySQL-python lib installed on centos 5.5. I ran
sudo yum install MySQL-python
but then when I tried:
import MySQLdb
I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "MySQLdb/__init__.py", line 22, in ?
raise ImportError("this is MySQLdb version %s, but _mysql is version %r" %
ImportError: this is MySQLdb version (1, 2, 3, 'final', 0), \ # added linebreak
but _mysql is version (1, 2, 1, 'final', 1)
any clues on how to fix this?
Step 1 - Install package
# yum install MySQL-python
Loaded plugins: auto-update-debuginfo, langpacks, presto, refresh-packagekit
Setting up Install Process
Resolving Dependencies
--> Running transaction check
---> Package MySQL-python.i686 0:1.2.3-3.fc15 will be installed
--> Finished Dependency Resolution
Dependencies Resolved
================================================================================
Package Arch Version Repository Size
================================================================================
Installing:
MySQL-python i686 1.2.3-3.fc15 fedora 78 k
Transaction Summary
================================================================================
Install 1 Package(s)
Total download size: 78 k
Installed size: 220 k
Is this ok [y/N]: y
Downloading Packages:
Setting up and reading Presto delta metadata
Processing delta metadata
Package(s) data still to download: 78 k
MySQL-python-1.2.3-3.fc15.i686.rpm | 78 kB 00:00
Running rpm_check_debug
Running Transaction Test
Transaction Test Succeeded
Running Transaction
Installing : MySQL-python-1.2.3-3.fc15.i686 1/1
Installed:
MySQL-python.i686 0:1.2.3-3.fc15
Complete!
Step 2 - Test working
import MySQLdb
db = MySQLdb.connect("localhost","myusername","mypassword","mydb" )
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print "Database version : %s " % data
db.close()
Ouput:
Database version : 5.5.20
I have Python 2.7.5, MySQL 5.6 and CentOS 7.1.1503.
For me it worked with the following command:
# pip install mysql-python
Note pre-requisites here:
Install Python pip:
# rpm -iUvh http://dl.fedoraproject.org/pub/epel/7/x86_64/e/epel-release-7-5.noarch.rpm
# yum -y update
Reboot the machine (if kernel is also updated)
# yum -y install python-pip
Install Python devel packages:
# yum install python-devel
Install MySQL devel packages:
# yum install mysql-devel
For centos7 I required:
sudo yum install mysql-devel gcc python-pip python-devel
sudo pip install mysql-python
So, gcc and mysql-devel (rather than mysql) were important
You probably did not install MySQL via yum? The version of MySQLDB in the repository is tied to the version of MySQL in the repository. The versions need to match.
Your choices are:
Install the RPM version of MySQL.
Compile MySQLDB to your version of
MySQL.
mysql-python NOT support Python3, you may need:
sudo pip3 install mysqlclient
Also, check this post for more alternatives.