开始使用免费开始使用

插入单行记录

使用 SQLAlchemy 进行插入有多种方式;不过,我们将重点介绍与 select 语句相同模式的一种。

它使用 insert 语句:将表作为参数传入,并通过 .values() 方法以关键字参数的形式提供待插入的数据。例如,如果 my_table 包含列 my_col_1my_col_2,那么 insert(my_table).values(my_col_1=5, my_col_2="Example") 会在 my_table 中创建一行,其中 my_col_1 的值为 5,my_col_2 的值为 "Example"

请注意语法差异:当在已有语句后追加 where 子句时,需要同时包含表名和列名,例如 new_stmt = old_stmt.where(my_tbl.columns.my_col == 15)。这是必要的,因为已有语句可能涉及多张表。

另一方面,insert 只能向单个表插入记录,所以在使用 values() 插入时无需包含表名,例如 stmt = insert(my_table).values(my_col = 10)

这里,表名是 data。您可以在控制台中运行 repr(data) 来查看该表的结构。

本练习是课程的一部分

Python 中的数据库入门

查看课程

练习说明

  • sqlalchemy 模块导入 insertselect
  • 构建针对 data 表的插入语句 insert_stmt,将 name 设为 'Anna'count 设为 1amount 设为 1000.00valid 设为 True
  • 使用 connection 执行 insert_stmt,并将结果保存为 results
  • 打印 results.rowcount 属性,以查看插入了多少条记录。
  • 构建一个 select 语句,从 data 中查询 name'Anna' 的记录。
  • 运行解答以打印执行该 select 语句的结果。

交互式实操练习

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

# Import insert and select from sqlalchemy
from sqlalchemy import ____, ____

# Build an insert statement to insert a record into the data table: insert_stmt
insert_stmt = insert(____).values(name=____, ____, ____, ____)

# Execute the insert statement via the connection: results
results = connection.execute(____)

# Print result rowcount
print(____)

# Build a select statement to validate the insert: select_stmt
select_stmt = select([data]).where(____ == ____)

# Print the result of executing the query.
print(connection.execute(select_stmt).first())
编辑并运行代码