Python MariaDB – 使用 PyMySQL 按条款排序
当我们必须将 MySQL 与其他编程语言一起使用时,就会使用 MySQL 客户端库。 PyMySQL的工作是提供对 MySQL Driver 的访问所需的语言。因此,它会在编程语言和 MySQL 服务器之间生成连接。
订单条款
OrderBy用于按升序或降序排列结果集。默认情况下,它总是按升序排列,除非提到“DESC”,它按降序排列。 “ASC”也可用于明确地按升序排列。但是,通常不会这样做,因为默认已经这样做了。
句法 :
SELECT column_list
FROM table_name
ORDER BY column_name ASC|DESC;
以下程序将帮助您更好地理解这一点。
使用中的表:
示例 1:按PRODUCT_TYPE按升序排列数据的程序
Python3
import pymysql
# Create a connection object
# IP address of the MySQL database server
Host = "localhost"
# User name of the database server
User = "user"
# Password for the database user
Password = ""
database = "GFG"
conn = pymysql.connect(host=Host, user=User, password=Password, database)
# Create a cursor object
cur = conn.cursor()
query = f"SELECT * FROM PRODUCT ORDER BY PRODUCT_TYPE ASC"
cur.execute(query)
rows = cur.fetchall()
for row in rows :
print(row)
conn.close()
Python3
import pymysql
# Create a connection object
conn = pymysql.connect('localhost', 'user',
'password', 'database')
# Create a cursor object
cur = conn.cursor()
query = f"SELECT * FROM PRODUCT ORDER BY price DESC"
cur.execute(query)
for row in rows :
print(row)
conn.close()
Python3
import pymysql
# Create a connection object
conn = pymysql.connect('localhost', 'user',
'password', 'database')
# Create a cursor object
cur = conn.cursor()
query = f"SELECT price,PRODUCT_TYPE FROM PRODUCT\
ORDER BY price ASC"
cur.execute(query)
for row in rows :
print(row)
conn.close()
输出 :
示例 2:按价格降序排列表格
蟒蛇3
import pymysql
# Create a connection object
conn = pymysql.connect('localhost', 'user',
'password', 'database')
# Create a cursor object
cur = conn.cursor()
query = f"SELECT * FROM PRODUCT ORDER BY price DESC"
cur.execute(query)
for row in rows :
print(row)
conn.close()
输出 :
示例 3:按价格升序排列表格
蟒蛇3
import pymysql
# Create a connection object
conn = pymysql.connect('localhost', 'user',
'password', 'database')
# Create a cursor object
cur = conn.cursor()
query = f"SELECT price,PRODUCT_TYPE FROM PRODUCT\
ORDER BY price ASC"
cur.execute(query)
for row in rows :
print(row)
conn.close()
输出 :