自定义 SQL 查询的 Hello World
恭喜您执行了第一个 SQL 查询!现在,您将学习如何自定义查询,以便:
- 从表中选择指定的列;
- 选择指定数量的行;
- 从数据库表中导入列名。
回顾一下,Hugo 在视频中也进行了非常相似的查询自定义:
engine = create_engine('sqlite:///Northwind.sqlite')
with engine.connect() as con:
rs = con.execute("SELECT OrderID, OrderDate, ShipName FROM Orders")
df = pd.DataFrame(rs.fetchmany(size=5))
df.columns = rs.keys()
所需的包已按如下方式导入:
from sqlalchemy import create_engine
import pandas as pd
引擎也已经创建:
engine = create_engine('sqlite:///Chinook.sqlite')
引擎连接已通过以下语句打开:
with engine.connect() as con:
您需要完成的所有代码都在此上下文中。
本练习是课程的一部分
Python 数据导入入门
练习说明
- 执行一个 SQL 查询,从
Employee表中 选择 列LastName和Title。将结果存入变量rs。 - 对
rs应用fetchmany()方法以获取 3 条记录。将它们存入 DataFramedf。 - 使用
rs对象,将 DataFrame 的列名设置为表中对应的列名。
交互式实操练习
通过完成这段示例代码来试试这个练习。
# Open engine in context manager
# Perform query and save results to DataFrame: df
with engine.connect() as con:
rs = ____
df = pd.DataFrame(____)
df.columns = ____
# Print the length of the DataFrame df
print(len(df))
# Print the head of the DataFrame df
print(df.head())