Retrieving the data

To retrieve the data from the table, we use the select statement. Now, we are going to retrieve the data from our books table. For that, create a retrieve_data.py script and write the following content in it:

import MySQLdb as mdb

con_obj = mdb.connect('localhost', 'test_user', 'test123', 'test')
with con_obj:
cur_obj = con_obj.cursor()
cur_obj.execute("SELECT * FROM books")
records = cur_obj.fetchall()
for r in records:
print(r)

Run the script and you will get the output as follows:

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

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

In the preceding example, we retrieved data from tables. We used the MySQLdb module. We wrote a connection string and created a cursor object to execute the SQL query. In execute(), we wrote an SQL select statement. And last, we printed the records.

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

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