將資料插入資料表

Python 資料庫入門

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

新增資料到資料表

  • 使用 insert() 陳述式
  • insert() 以要載入資料的資料表為引數
  • 透過 values 子句加入要插入的值,格式為 column=value 配對
  • 不會回傳任何列,因此不需要 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...