Inserting data into a table

Introduction to Databases in Python

Jason Myers

Co-Author of Essential SQLAlchemy and Software Engineer

Adding data to a table

  • Done with the insert() statement
  • insert() takes the table we are loading data into as the argument
  • We add all the values we want to insert in with the values clause as column=value pairs
  • Doesn't return any rows, so no need for a fetch method
Introduction to Databases in Python

Inserting one row

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
Introduction to Databases in Python

Inserting multiple rows

  • Build an insert statement without any values
  • Build a list of dictionaries that represent all the values clauses for the rows you want to insert
  • Pass both the statement and the values list to the execute method on connection
Introduction to Databases in Python

Inserting multiple rows

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
Introduction to Databases in Python

Let's practice!

Introduction to Databases in Python

Preparing Video For Download...