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:
- 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.
-
Install
psycopg2
andpython-dotenv
in your project's root directory. You can install them usingpip
:
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 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?
Join our Discord Server to ask questions or see what others are doing with Neon. Users on paid plans can open a support ticket from the console. For more detail, see Getting Support.
Last updated on