开始使用免费开始使用

Creating tables with SQLAlchemy

Previously, you used the Table object to reflect a table from an existing database, but what if you wanted to create a new table? You'd still use the Table object; however, you'd need to replace the autoload and autoload_with parameters with Column objects.

The Column object takes a name, a SQLAlchemy type with an optional format, and optional keyword arguments for different constraints.

When defining the table, recall how in the video Jason passed in 255 as the maximum length of a String by using Column('name', String(255)). Checking out the slides from the video may help.

After defining the table, you can create the table in the database by using the .create_all() method on metadata and supplying the engine as the only parameter. Go for it!

本练习是课程的一部分

Introduction to Databases in Python

查看课程

练习说明

  • Import Table, Column, String, Integer, Float, Boolean from sqlalchemy.
  • Build a new table called data with columns 'name' (String(255)), 'count' (Integer()), 'amount'(Float()), and 'valid' (Boolean()) columns. The second argument of Table() needs to be metadata, which has already been initialized.
  • Create the table in the database by passing engine to metadata.create_all().

交互式实操练习

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

# Import Table, Column, String, Integer, Float, Boolean from sqlalchemy
from sqlalchemy import ____, ____, ____, ____, ____, ____

# Define a new table with a name, count, amount, and valid column: data
data = Table('data', ____,
             Column(____, ____),
             Column('count', Integer()),
             Column(____, ____),
             Column(____, ____)
)

# Use the metadata to create the table
metadata.create_all(____)

# Print table details
print(repr(data))
编辑并运行代码