Powering next gen AI apps with Postgres 🚀 Learn More
Guides/Languages/Python

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.

To connect:

  1. Create a Neon Project
  2. Create a Python project
  3. Store your Neon credentials
  4. Configure your Python script
  5. Test your connection

Create a Neon project

If you do not have one already, create a Neon project.

  1. Navigate to the Projects page in the Neon Console.
  2. Click New Project.
  3. 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

  1. Create a project directory and change to the newly created directory.

  2. 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.

  3. Activate the virtual environment. When the virtual environment is activated, Python uses the environment's version of Python and any installed packages.

  4. Install psycopg2 and python-dotenv in your project's root directory. You can install them using pip:

Store your Neon credentials

Add a .env file to your project's root directory and add your Neon connection string to it. You will find the connection string for your database 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

Add a 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

Run the neon-connect.py script to test your connection.

If the connection is successful, the script returns information similar to the following:

Need help?

Send a request to support@neon.tech, or join the Neon community forum.

Edit this page
Was this page helpful?