- Python & MySQL Tutorial
- Python & MySQL - Home
- Python & MySQL - Overview
- Python & MySQL - Environment Setup
- Python & MySQL Examples
- Python & MySQL - Connect Database
- Python & MySQL - Create Database
- Python & MySQL - Drop Database
- Python & MySQL - Select Database
- Python & MySQL - Create Tables
- Python & MySQL - Drop Tables
- Python & MySQL - Insert Records
- Python & MySQL - Select Records
- Python & MySQL - Update Records
- Python & MySQL - Delete Records
- Python & MySQL - Where Clause
- Python & MySQL - Like Clause
- Python & MySQL - Sorting Data
- Python & MySQL - Using Joins
- Python & MySQL - Performing Transactions
- Python & MySQL - Handling Errors
- Python & MySQL Useful Resources
- Python & MySQL - Quick Guide
- Python & MySQL - Useful Resources
- Python & MySQL - Discussion
Python & MySQL - Sorting Data Example
Python uses c.execute(q) function to select a record(s) in sorted order using sort by Statement from a table where c is cursor and q is the select query to be executed.
Syntax
# execute SQL query using execute() method. cursor.execute(sql) result = cursor.fetchall() for record in result: print(record)
Sr.No. | Parameter & Description |
---|---|
1 | $sql Required - SQL query to select record(s) from a table and sort using sort by Statement. |
Example
Try the following example to select sorted records from a table using sort by Statement −
Copy and paste the following example as mysql_example.ty −
#!/usr/bin/python import MySQLdb # Open database connection db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS") # prepare a cursor object using cursor() method cursor = db.cursor() sql = "Select * from tutorials_tbl order by tutorial_title asc" # execute SQL query using execute() method. cursor.execute(sql) # fetch all records from cursor result = cursor.fetchall() # iterate result and print records for record in result: print(record) # disconnect from server db.close()
Output
Execute the mysql_example.py script using python and verify the output.
(1, 'HTML 5', 'Robert', datetime.date(2010, 2, 10)) (2, 'Java', 'Julie', datetime.date(2020, 12, 10)) (3, 'JQuery', 'Julie', datetime.date(2020, 5, 10))
Advertisements
To Continue Learning Please Login
Login with Google