开始使用免费开始使用

从数据库读取数据

在本练习中,您将从本地 PostgreSQL 数据库的表中抽取数据。您将使用的数据来自 Pagila 示例数据库。该数据库为一个虚构的 DVD 商店应用提供支持,教育资源常将其作为示例数据库使用。

您将创建并使用一个函数,把数据库表提取为一个 pandas DataFrame 对象。您将要提取的表包括:

  • film:DVD 商店出租的影片。
  • customer:在 DVD 商店租片的顾客。

为连接数据库,您需要使用 PostgreSQL 连接 URI,其形式如下:

postgresql://[user[:password]@][host][:port][/database]

本练习是课程的一部分

Data Engineering 入门

查看课程

练习说明

  • 完成 extract_table_to_pandas() 函数定义,在查询中加入 tablename 参数。
  • 填写连接 URI。用户名和密码分别为 replpassword;主机为 localhost,端口为 5432;数据库为 pagila
  • 完成对 extract_table_to_pandas() 的函数调用,提取 film 和 customer 两个表。

交互式实操练习

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

# Function to extract table to a pandas DataFrame
def extract_table_to_pandas(tablename, db_engine):
    query = "SELECT * FROM {}".format(____)
    return pd.read_sql(query, db_engine)

# Connect to the database using the connection URI
connection_uri = "postgresql://____:____@____:____/____" 
db_engine = sqlalchemy.create_engine(connection_uri)

# Extract the film table into a pandas DataFrame
extract_table_to_pandas("____", db_engine)

# Extract the customer table into a pandas DataFrame
extract_table_to_pandas("____", db_engine)
编辑并运行代码