SQLAlchemy Core
- Using Set Operations
- Using Functions
- Using Conjunctions
- Using Joins
- Multiple Table Deletes
- Parameter-Ordered Updates
- Using Multiple Table Updates
- Using Multiple Tables
- Using DELETE Expression
- Using UPDATE Expression
- Using Aliases
- Using Textual SQL
- Selecting Rows
- Executing Expression
- SQL Expressions
- Creating Table
- Connecting to Database
- Expression Language
SQLAlchemy ORM
- Dialects
- Many to Many Relationships
- Deleting Related Objects
- Eager Loading
- Common Relationship Operators
- Working with Joins
- Working with Related Objects
- Building Relationship
- Textual SQL
- Returning List and Scalars
- Filter Operators
- Applying Filter
- Updating Objects
- Using Query
- Adding Objects
- Creating Session
- Declaring Mapping
SQLAlchemy Useful Resources
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Using UPDATE Expression
The update() method on target table object constructs equivalent UPDATE SQL expression.
table.update().where(conditions).values(SET expressions)
The values() method on the resultant update object is used to specify the SET conditions of the UPDATE. If left as None, the SET conditions are determined from those parameters passed to the statement during the execution and/or compilation of the statement.
The where clause is an Optional expression describing the WHERE condition of the UPDATE statement.
Following code snippet changes value of ‘lastname’ column from ‘Khanna’ to ‘Kapoor’ in students table −
stmt = students.update().where(students.c.lastname == Khanna ).values(lastname = Kapoor )
The stmt object is an update object that translates to −
UPDATE students SET lastname = :lastname WHERE students.lastname = :lastname_1
The bound parameter lastname_1 will be substituted when execute() method is invoked. The complete update code is given below −
from sqlalchemy import create_engine, MetaData, Table, Column, Integer, String engine = create_engine( sqpte:///college.db , echo = True) meta = MetaData() students = Table( students , meta, Column( id , Integer, primary_key = True), Column( name , String), Column( lastname , String), ) conn = engine.connect() stmt=students.update().where(students.c.lastname== Khanna ).values(lastname= Kapoor ) conn.execute(stmt) s = students.select() conn.execute(s).fetchall()
The above code displays following output with second row showing effect of update operation as in the screenshot given −
[ (1, Ravi , Kapoor ), (2, Rajiv , Kapoor ), (3, Komal , Bhandari ), (4, Abdul , Sattar ), (5, Priya , Rajhans ) ]
Note that similar functionapty can also be achieved by using update() function in sqlalchemy.sql.expression module as shown below −
from sqlalchemy.sql.expression import update stmt = update(students).where(students.c.lastname == Khanna ).values(lastname = Kapoor )Advertisements