Reputation: 588
I created a postgresql database and I want to link it to my python code using sqlalchemy, but since I made the database in pgadmin, I don't know what to mention as the URL of the database in the code.
Upvotes: 18
Views: 60043
Reputation: 20231
If you are on a mac you can start the shell by running
psql postgres
assuming that you have started the postgreSQL server by running
pg_ctl -D /opt/homebrew/var/postgresql@14 start
and then check the connection info using \conninfo
which should output something like this
properties:
You are connected to database "postgres" as user "mahesh" via socket in "/tmp" at port "5432"
you can also find these details by selecting the server in the side bar and select properties at the top.
And you can create the connection string using those details in this format
jdbc:postgresql://<host>:<port>/<database_name>?user=<username>&password=<password>
source: https://pastelog.vercel.app/logs/publish/11eHLHCb5yn1KdgP5u5t/
Upvotes: 0
Reputation: 899
With the upper picture setting. I use following pattern
postgresql://postgres:[MY_PASSWORD]@localhost:5432/[DATABASE_NAME]
postgresql://[YOUR_USERNAME]:[YOUR_PASSWORD]@[YOUR_HOST_NAME]:[YOUR_PORT]/[DATABASE_NAME]
Upvotes: 4
Reputation: 123484
Go back into pgAdmin, click on the node for your server and then check the values under "Connection" in the "Properties" page:
According to the SQLAlchemy documentation the corresponding connection URL for those values would be
connection_url = 'postgresql+psycopg2://user:password@localhost:5432/db_name'
engine = create_engine(connection_url)
Upvotes: 10
Reputation: 1563
If you created your database using the defaults, you can probably login to the server using psql (SQL Shell).
Try to connect to the database you created and if you are able to connect to the database try \conninfo
.
If it's on your own machine the output will be quite standard host will be localhost
, ip will be 127.0.0.1
and port will be the default port of 5432
.
Once you make sure of these things you should try to connect to the database using the following code from this answer to a different question.
Please make sure you have both SQLAlchemy and psycopg2 installed before you try to connect. Then try this:
from sqlalchemy import create_engine
engine = create_engine('postgresql+psycopg2://user:password@hostname/database_name')
Or may be find a good tutorial on SQLAlchemy.
Upvotes: 15