這是我的數據庫student,好比輸入一個值為32,查詢id最接近32的整行數據,可以用以下代碼
import pymysql value=32 conn = pymysql.connect(host='39.106.168.84', user='xxxxxxx', password='xxxxxxx', port=3306, db='flask_topvj_net') cur = conn.cursor() sql="select * from `student` order by abs(`id` - '%s') limit 1" %(value) cur.execute(sql) u = cur.fetchall() print(u) conn.close()
運行結果為