向表中插入数据

Python 中的数据库入门

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

向表添加数据

  • 使用 insert() 语句
  • insert() 的参数是要写入的表
  • values 子句中以 列=值 成对提供要插入的值
  • 不返回行,无需使用 fetch 方法
Python 中的数据库入门

插入一行

from sqlalchemy import insert
stmt = insert(employees).values(id=1,name='Jason', 
          salary=1.00, active=True)

result_proxy = connection.execute(stmt) print(result_proxy.rowcount)
1
Python 中的数据库入门

插入多行

  • 构建不含值的 insert 语句
  • 构建一个字典列表,每个字典对应一行的 values 子句
  • 将语句和值列表一起传给 connection 的 execute 方法
Python 中的数据库入门

插入多行

stmt = insert(employees)

values_list = [{'id': 2, 'name': 'Rebecca', 'salary': 2.00, 'active': True}, {'id': 3, 'name': 'Bob', 'salary': 0.00, 'active': False}]
result_proxy = connection.execute(stmt, values_list)
print(result_proxy.rowcount)
2
Python 中的数据库入门

开始练习!

Python 中的数据库入门

Preparing Video For Download...