python pymysql 按照int表排序
时间: 2023-12-31 21:05:58 浏览: 64
可以使用SQL语句来实现按照int表排序,具体如下:
1. 连接数据库
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='database')
```
2. 构造SQL语句
假设需要按照表中的age字段排序,则可以构造如下SQL语句:
```python
sql = "SELECT * FROM table_name ORDER BY age ASC"
```
其中,table_name为需要排序的表名,age为需要按照其排序的字段名。
3. 执行SQL语句
```python
# 执行SQL语句
cursor = conn.cursor()
cursor.execute(sql)
# 获取结果集
results = cursor.fetchall()
# 输出结果
for row in results:
print(row)
```
完整代码示例:
```python
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='password', db='database')
# 构造SQL语句
sql = "SELECT * FROM table_name ORDER BY age ASC"
# 执行SQL语句
cursor = conn.cursor()
cursor.execute(sql)
# 获取结果集
results = cursor.fetchall()
# 输出结果
for row in results:
print(row)
# 关闭连接
conn.close()
```
阅读全文