Home:ALL Converter>Connecting postgresql with sqlalchemy

Connecting postgresql with sqlalchemy

Ask Time:2012-02-20T06:17:44         Author:Jack_of_All_Trades

Json Formatter

I know this might be really a simple question but I don't know the solution. What is happening here when I try to connect to postgresql? I am self learner in this field of database and programming so please be gentle with me. When I try following code:

import sqlalchemy
db = sqlalchemy.create_engine('postgresql:///tutorial.db')

I get this error:

Traceback (most recent call last): File "", line 1, in db = sqlalchemy.create_engine('postgresql:///tutorial.db') File "C:\Python27\lib\site-packages\sqlalchemy-0.7.5dev-py2.7.egg\sqlalchemy\engine__init__.py", line 327, in create_engine return strategy.create(*args, **kwargs) File "C:\Python27\lib\site-packages\sqlalchemy-0.7.5dev-py2.7.egg\sqlalchemy\engine\strategies.py", line 64, in create dbapi = dialect_cls.dbapi(**dbapi_args) File "C:\Python27\lib\site-packages\sqlalchemy-0.7.5dev-py2.7.egg\sqlalchemy\dialects\postgresql\psycopg2.py", line 289, in dbapi psycopg = import('psycopg2') ImportError: No module named psycopg2

Do I need to install psycopg2 separately? What is the correct connection string for postgresql?

Author:Jack_of_All_Trades,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/9353822/connecting-postgresql-with-sqlalchemy
Uku Loskit :

Yes, psycopg2 are basically the Python drivers for PostgreSQL that need to be installed separately.\n\nA list of valid connection strings can be found here, yours is a bit off (you need to the username, the password and hostname as specified in the link below):\n\nhttp://docs.sqlalchemy.org/en/latest/core/engines.html#postgresql",
2012-02-19T22:19:17
andrew :

You would need to pip install SQLAlchemy and pip install psycopg2.\nAn example of a SQLAlchemy connection string that uses psycopg2:\n\nfrom sqlalchemy import create_engine\nengine = create_engine('postgresql+psycopg2://user:password@hostname/database_name')\n\n\nYou could also connect to your database using the psycopg2 driver exclusively:\n\nimport psycopg2\nconn_string = \"host='localhost' dbname='my_database' user='postgres' password='secret'\"\nconn = psycopg2.connect(conn_string)\n\n\nHowever, using the psycopg2 driver to connect does not take advantage of SQLAlchemy.",
2017-03-03T19:33:03
yy