CommencerCommencer gratuitement

Connecting to a PostgreSQL database

In these exercises, you will be working with real databases hosted on the cloud via Amazon Web Services (AWS)!

Let's begin by connecting to a PostgreSQL database. When connecting to a PostgreSQL database, many prefer to use the psycopg2 database driver as it supports practically all of PostgreSQL's features efficiently and is the standard dialect for PostgreSQL in SQLAlchemy.

You might recall from Chapter 1 that we use the create_engine() function and a connection string to connect to a database. In general, connection strings have the form "dialect+driver://username:password@host:port/database"

There are three components to the connection string in this exercise: the dialect and driver ('postgresql+psycopg2://'), followed by the username and password ('student:datacamp'), followed by the host and port ('@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com:5432/'), and finally, the database name ('census'). You will have to pass this string as an argument to create_engine() in order to connect to the database.

Cet exercice fait partie du cours

Introduction to Databases in Python

Afficher le cours

Instructions

  • Import create_engine from sqlalchemy.
  • Create an engine to the census database by concatenating the following strings:
    • 'postgresql+psycopg2://'
    • 'student:datacamp'
    • '@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com'
    • ':5432/census'
  • Use the .table_names() method on engine to print the table names.

Exercice interactif pratique

Essayez cet exercice en complétant cet exemple de code.

# Import create_engine function
from ____ import create_engine

# Create an engine to the census database
engine = create_engine(____)

# Use the .table_names() method on the engine to print the table names
print(____)
Modifier et exécuter le code