Python基础 之 Python MySQL - mysql-connector 驱动 11
Python MySQL - mysql-connector 驱动
排序
查询结果排序可以使用 ORDER BY 语句,默认的排序方式为升序,关键字为 ASC,如果要设置降序排序,可以设置关键字 DESC。
demo_mysql_test.py
按 name 字段字母的升序排序:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="123456",
database="baidu_db"
)
mycursor = mydb.cursor()
sql = "SELECT * FROM sites ORDER BY name"
mycursor.execute(sql)
myresult = mycursor.fetchall()
for x in myresult:
print(x)
执行代码,输出结果为:
(3, 'Github', 'https://www.github.com')
(2, 'Google', 'https://www.google.com')
(1, 'baidu', 'https://www.baidu.com')
(5, 'stackoverflow', 'https://www.stackoverflow.com/')
(4, 'Taobao', 'https://www.taobao.com')
(6, 'Zhihu', 'https://www.zhihu.com')