Updating the data

Now, if we want to make some changes in the records, we can use an SQL update statement. We are going to see an example of an update statement. For that, create a update_data.py script and write following content in it:

import MySQLdb as mdb

con_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
cur_obj = con_obj.cursor()
cur_obj.execute("UPDATE books SET Name = 'Fantastic Beasts' WHERE Id = 1")
try:
con_obj.commit()
except:
con_obj.rollback()

Run the script as follows:

student@ubuntu:~/work/mysql_testing$ python3 update_data.py

Now, to check if your record is updated or not, run retrieve_data.py as follows:

student@ubuntu:~/work/mysql_testing$ python3 retrieve_data.py

Output:
(1, 'Fantastic Beasts')
(2, 'Lord of the rings')
(3, 'Murder on the Orient Express')
(4, 'The adventures of Sherlock Holmes')
(5, 'Death on the Nile')

You can see your data for ID 1 is updated. In the preceding example, in execute(), we have written an update statement that will update the data for ID 1.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset