Python MySQL – 按子句排序
当我们必须将 MySQL 与其他编程语言一起使用时,就会使用连接器。 MySQL-connector 的工作是提供对 MySQL Driver 所需语言的访问。因此,它会在编程语言和 MySQL 服务器之间生成连接。
OrderBy 条款
OrderBy 用于按升序或降序排列结果集。默认情况下,除非提到“DESC”,否则它始终按升序排列,它按降序排列。
“ASC”也可以用来明确地按升序排列。但是,通常不会这样做,因为默认已经这样做了。
句法-
SELECT column1, column2
FROM table_name
ORDER BY column_name ASC|DESC;
以下程序将帮助您更好地理解这一点。
使用中的数据库:
示例 1:按名称升序排列数据的程序
# Python program to demonstrate
# order by clause
import mysql.connector
# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
password = ''
)
cs = mydb.cursor()
# Order by clause
statement ="SELECT * FROM Student ORDER BY Name"
cs.execute(statement)
result_set = cs.fetchall()
for x in result_set:
print(x)
# Disconnecting from the database
mydb.close()
输出:
示例 2:按降序排列数据库
# Python program to demonstrate
# order by clause
import mysql.connector
# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
)
cs = mydb.cursor()
# Order by clause
statement ="SELECT * FROM Student ORDER BY Name DESC"
cs.execute(statement)
result_set = cs.fetchall()
for x in result_set:
print(x)
# Disconnecting from the database
mydb.close()
输出:
示例 3:程序从表中获取名称,按卷号降序排列。
# Python program to demonstrate
# order by clause
import mysql.connector
# Connecting to the Database
mydb = mysql.connector.connect(
host ='localhost',
database ='College',
user ='root',
)
cs = mydb.cursor()
# Order by clause
statement ="SELECT Name FROM Student ORDER BY Roll_no DESC"
cs.execute(statement)
result_set = cs.fetchall()
for x in result_set:
print(x)
# Disconnecting from the database
mydb.close()
输出: