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.
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 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
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
I am trying to connect to a SQL Database hosted in Windows Azure through MySQLdb with Python.
I keep getting an error mysql_exceptions.OperationalError: (2001, 'Bad connection string.')
This information works when connecting through .NET (vb, C#) but I am definitely not having any luck here.
For below I used my server's name from azure then .database.windows.net Is this the correct way to go about this?
Here is my code:
#!/usr/bin/python
import MySQLdb
conn = MySQLdb.connect(host="<servername>.database.windows.net", user="myUsername", passwd="myPassword", db="db_name")
cursor = conn.cursor()
I have also tried using pyodbc with FreeTDS with no luck.
#Kyle Moffat, what OS are you on? Here is how you can use pyodbc on Linux and Windows:
https://msdn.microsoft.com/en-us/library/mt763261(v=sql.1).aspx
Windows:
Download and install Python
Install the Microsoft ODBC Driver 11 or 13:
v13: https://www.microsoft.com/en-us/download/details.aspx?id=50420
v11: https://www.microsoft.com/en-us/download/details.aspx?id=36434
Open cmd.exe as an administrator
Install pyodbc using pip - Python package manager
cd C:\Python27\Scripts>
pip install pyodbc
Linux:
Open terminal
Install Microsoft ODBC Driver 13 for Linux For Ubuntu 15.04 +
sudo su
wget https://gallery.technet.microsoft.com/ODBC-Driver-13-for-Ubuntu-b87369f0/file/154097/2/installodbc.sh
sh installodbc.sh
For RedHat 6,7
sudo su
wget https://gallery.technet.microsoft.com/ODBC-Driver-13-for-SQL-8d067754/file/153653/4/install.sh
sh install.sh
Install pyodbc
sudo -H pip install pyodbc
Once you install the ODBC driver and pyodbc you can use this Python sample to connect to Azure SQL DB
import pyodbc
server = 'tcp:myserver.database.windows.net'
database = 'mydb'
username = 'myusername'
password = 'mypassword'
cnxn = pyodbc.connect('DRIVER={ODBC Driver 13 for SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("SELECT ##version;")
row = cursor.fetchone()
while row:
print row[0]
row = cursor.fetchone()
If you are not able to install the ODBC Driver you can also try pymssql + FreeTDS
sudo apt-get install python
sudo apt-get --assume-yes install freetds-dev freetds-bin
sudo apt-get --assume-yes install python-dev python-pip
sudo pip install pymssql==2.1.1
Once you follow these steps, you can use the following code sample to connect:
https://msdn.microsoft.com/en-us/library/mt715796(v=sql.1).aspx