If you’re working on a Python project, you often need a database to store information. PostgreSQL is one of the most popular database systems available today. In this guide, we’ll walk you through how to connect your Postgres with Python.
In order to write Python scripts that can interact with a PostgreSQL database, you’ll need to install and import a PostgreSQL adapter. There are multiple options, but the most popular Postgres driver for Python is Psycopg2. Activate the virtual environment for your project and use pip to install:
pip install psycopg2
You’ll need to have your Postgres credentials. You can use this guide to find your credentials.
Once you have your credentials, import the
psycopg2 driver and create a new connection:
connection = psycopg2.connect( user = "myUser", password = "myPassword", host = "localhost", port = "5432", database = "myDB"
We can then open a cursor to start performing operations:
Once you have established your connection, you can query your Postgres database using Python. To create and run a query, use
cursor.execute() like this:
cursor.execute(“SELECT ‘Arctype Archive: Your #1 Database Resource’ as message”);
You can also pass variables to
cursor.execute() for both text and values parameters like this:
text = “INSERT INTO Users(username, email) VALUES(%s, %s) RETURNING *” values = (“Arctype”,”[firstname.lastname@example.org](mailto:email@example.com)”) cursor.execute(text, values)
You can get your results using the
results = cursor.fetchall()
Now that you’ve connected Postgres to your Python project, you often need to add or edit data. We recommend using an SQL client to do so. Check out our guide for setting up Postgres with Arctype in this tutorial.