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.
This is a part of the course
“Introduction to Databases in Python”
Exercise instructions
- Import
create_engine
fromsqlalchemy
. - 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 onengine
to print the table names.
Hands-on interactive exercise
Have a go at this exercise by completing this sample 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(____)