Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
221 views
in Technique[技术] by (71.8m points)

python - Connecting postgresql with sqlalchemy

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:Python27libsite-packagessqlalchemy-0.7.5dev-py2.7.eggsqlalchemyengine__init__.py", line 327, in create_engine return strategy.create(*args, **kwargs) File "C:Python27libsite-packagessqlalchemy-0.7.5dev-py2.7.eggsqlalchemyenginestrategies.py", line 64, in create dbapi = dialect_cls.dbapi(**dbapi_args) File "C:Python27libsite-packagessqlalchemy-0.7.5dev-py2.7.eggsqlalchemydialectspostgresqlpsycopg2.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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You would need to pip install SQLAlchemy and pip install psycopg2. An example of a SQLAlchemy connection string that uses psycopg2:

from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://user:password@hostname/database_name')

You could also connect to your database using the psycopg2 driver exclusively:

import psycopg2
conn_string = "host='localhost' dbname='my_database' user='postgres' password='secret'"
conn = psycopg2.connect(conn_string)

However, using the psycopg2 driver to connect does not take advantage of SQLAlchemy.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...