Connect a Python application to Neon using Psycopg
Set up a Neon project in seconds and connect from a Python application using Psycopg
This guide describes how to create a Neon project and connect to it from a simple Python application using Psycopg (psycopg2), a popular Postgres database adapter for the Python programming language. The application connects to Neon and retrieves the current time and Postgres version.
- Create a Neon Project
- Create a Python project
- Store your Neon credentials
- Configure your Python script
- Test your connection
Create a Neon project
If you do not have one already, create a Neon project.
- Navigate to the Projects page in the Neon Console.
- Click New Project.
- Specify your project settings and click Create Project.
The project is created with a ready-to-use
neondb database, which you will connect to.
Create a Python project
Create a project directory and change to the newly created directory.
Set up a Python virtual environment in this directory. The virtual environment isolates your project's Python environment (including installed packages) from the rest of your system.
Activate the virtual environment. When the virtual environment is activated, Python uses the environment's version of Python and any installed packages.
python-dotenvin your project's root directory. You can install them using
Store your Neon credentials
.env file to your project's root directory and add your Neon connection string to it.
You can find all of the connection details listed above in the Connection Details widget on the Neon Dashboard. For more information, see Connect from any application.
Your connection string will look something like this:
Configure your python script
neon-connect.py file to your project's root directory and add the following code. The script connects to your Neon database and retrieves the current time and Postgres version.
Test your connection
neon-connect.py script to test your connection.
If the connection is successful, the script returns information similar to the following:
Last updated on