Python Data Persistence – Core – Inserting Records

Python Data Persistence – Core – Inserting Records

Next, is how to insert a record in this table? For this purpose, use the insert ( ) construct on the table. It will produce a template INSERT query.

Example

>>> ins=Products.insert()
>>> str(ins)
'INSERT INTO "Products" ("ProductID", name, "Price")
VALUES (:ProductID, :name, :Price)'

We need to put values in the placeholder parameters and submit the ins object to our database engine for execution.

Example

ins.values(name="Laptop",Price=25000) 
con=engine.connect( )
con.execute(ins)

Selecting data from table is also straightforward. There is a select() function that constructs a new Select object.

Example

>>> s=Products.select()
>>> str(s)
'SELECT "Products"."ProductID", "Products".name,
"Products"."Price" \nFROM "Products"'

Provide this Select object to execute the () function. It now returns a result set from which one (fetch one) or all records (fetchall) can be fetched.

Example

>>> result=con.execute(s)
>>> for row in result:
... print (row)