Web Programming with Python: Limit, Update and Delete

In this tutorial we will learn about Limit, update and delete.

LIMIT
To understand the concept of Limit we make the following changes to the read_data_from_database() function as follows:

def read_data_from_database():
       sql = “SELECT * FROM example LIMIT 2”
       for row in c.execute(sql):
             print (row)

UPDATE
This will output first two rows of data:

(‘Python’, 2.7, ‘Beginner’)
 (‘Python’, 3.3, ‘Intermediate’)

Limit is generally used while updating or deleting or sometimes you may want to have a look at some number of rows in the database.

Now, look at how the UPDATE command works. UPDATE is used to edit the information in the database. Let’s say that we want to find out which rows have skill as “Beginner” and then change it to value of “beginner”.

def read_data_from_database():
       sql = “UPDATE example SET skill=’beginner ’ where skill =’Beginner ’”
      c.execute(sql):
       sql = “SELECT * FROM example”
       for row in c.execute(sql):
             print (row)

Now if you execute the code, you will get the following output:

(‘Python’, 2.7, ‘beginner’)
(‘Python’, 3.3, ‘Intermediate’)
(‘Python’, 3.4, ‘Expert’)

DELETE
Now , let’s try to delete the row that has skill value of ‘beginner’.

def read_data_from_database():
        sql = “SELECT * FROM example”
       for row in c.execute(sql):
             print (row)
       print(20*’#’)
      sql = “DELETE * FROM example where skill=’Beginner’”
      c.execute(sql):
for row in c.execute(sql):
             print (row)
conn.commit()

So, the output now will be:

(‘Python’, 2.7, ‘beginner’)
(‘Python’, 3.3, ‘Intermediate’)
(‘Python’, 3.4, ‘Expert’)
####################
(‘Python’, 3.3, ‘Intermediate’)
(‘Python’, 3.4, ‘Expert’)

Online Technology Courses Stone River eLearning

GET YOUR FREE PYTHON EBOOK!

Comments