开始使用免费开始使用

连接到 PostgreSQL 数据库

在本练习中,您将通过 Amazon Web Services (AWS) 连接并操作真实的云端数据库!

我们先从连接 PostgreSQL 数据库开始。连接 PostgreSQL 时,许多人更喜欢使用 psycopg2 数据库驱动程序,因为它高效支持几乎所有 PostgreSQL 功能,并且是在 SQLAlchemy 中 PostgreSQL 的标准方言驱动。

您或许还记得第 1 章中,我们使用 create_engine() 函数和连接字符串来连接数据库。一般而言,连接字符串的格式为 "dialect+driver://username:password@host:port/database"

本练习的连接字符串由三部分组成:方言与驱动('postgresql+psycopg2://'),然后是用户名和密码('student:datacamp'),接着是主机与端口('@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com:5432/'),最后是数据库名('census')。您需要将该字符串作为参数传给 create_engine(),以便连接到数据库。

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • sqlalchemy 导入 create_engine
  • 通过拼接以下字符串来为 census 数据库创建一个引擎:
    • 'postgresql+psycopg2://'
    • 'student:datacamp'
    • '@postgresql.csrrinzqubik.us-east-1.rds.amazonaws.com'
    • ':5432/census'
  • engine 上使用 .table_names() 方法打印表名。

交互式实操练习

通过完成这段示例代码来试试这个练习。

# 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(____)
编辑并运行代码