Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,870 questions

51,793 answers

573 users

How to run SQL query in MySQL database with ORDER BY statement to sort the result in Python

2 Answers

0 votes
# c:\Users\user_nm\AppData\Local\Programs\Python\Python35-32\Scripts\pip install mysql-connector
    
import mysql.connector
    
db = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="",
    database="python_database"
)
   
db_cursor = db.cursor()

sql = "SELECT * FROM workers ORDER BY first_name"

db_cursor.execute(sql)

result = db_cursor.fetchall()
 
for row in result:
    print(row)
 
db.close()

 
'''
run:
  
(3, 'Amy', 'Python Programmer')
(4, 'Arthur', 'Java Programmer')
(2, 'Aurora', 'C++ Programming')
(1, 'Fox', 'C Programmer')
(5, 'R2D2', 'Super Programmer')
 
'''

 



answered Dec 2, 2018 by avibootz
0 votes
# c:\Users\user_nm\AppData\Local\Programs\Python\Python35-32\Scripts\pip install mysql-connector
    
import mysql.connector
    
db = mysql.connector.connect(
    host="localhost",
    user="root",
    passwd="",
    database="python_database"
)
   
db_cursor = db.cursor()

sql = "SELECT * FROM workers ORDER BY first_name DESC"

db_cursor.execute(sql)

result = db_cursor.fetchall()
 
for row in result:
    print(row)
 
db.close()

 
'''
run:
  
(5, 'R2D2', 'Super Programmer')
(1, 'Fox', 'C Programmer')
(2, 'Aurora', 'C++ Programming')
(4, 'Arthur', 'Java Programmer')
(3, 'Amy', 'Python Programmer')
 
'''

 



answered Dec 3, 2018 by avibootz
...