Watch Neon Developer Days #3 🚀

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

Add a 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 script to test your connection.

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

Need help?

Join the Neon community forum to ask questions or see what others are doing with Neon. Neon Pro Plan users can open a support ticket from the console. For more detail, see Getting Support.

Last updated on

Edit this page
Was this page helpful?