插入单行记录
使用 SQLAlchemy 进行插入有多种方式;不过,我们将重点介绍与 select 语句相同模式的一种。
它使用 insert 语句:将表作为参数传入,并通过 .values() 方法以关键字参数的形式提供待插入的数据。例如,如果 my_table 包含列 my_col_1 和 my_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模块导入insert和select。 - 构建针对
data表的插入语句insert_stmt,将name设为'Anna',count设为1,amount设为1000.00,valid设为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())