如何用Python自动化查找目标值的相邻上下数值并写入SQL表
实现SQL数据紧邻上下值的自动查询与存储
1. 从SQL数据库获取并排序数据
以SQLite为例,用Python连接数据库并取出所有数值排序:
import sqlite3 # 连接目标数据库 conn = sqlite3.connect('your_db_name.db') cursor = conn.cursor() # 查询所有数值并按升序排列 cursor.execute("SELECT value FROM your_source_table ORDER BY value ASC") sorted_values = [row[0] for row in cursor.fetchall()] conn.close()
如果是MySQL/PostgreSQL,替换为对应连接库(如pymysql/psycopg2)即可,核心查询逻辑不变。
2. 查找传入数值的紧邻上下值
编写函数处理目标数值,遍历已排序的列表找到边界值:
def get_neighbor_values(target, sorted_list): lower_bound = None upper_bound = None for val in sorted_list: if val < target: lower_bound = val elif val > target: upper_bound = val break # 列表已排序,找到第一个大于目标的值即可停止遍历 # 处理边界情况:目标小于所有值或大于所有值 if lower_bound is None: lower_bound = sorted_list[0] if sorted_list else None if upper_bound is None: upper_bound = sorted_list[-1] if sorted_list else None return lower_bound, upper_bound # 获取传入的目标数值(通过命令行参数传递,适配定时触发) import sys target_num = float(sys.argv[1]) lower_val, upper_val = get_neighbor_values(target_num, sorted_values)
3. 将结果写入目标SQL表
再次连接数据库,把结果插入指定表:
conn = sqlite3.connect('your_db_name.db') cursor = conn.cursor() # 插入数据到结果表 cursor.execute(""" INSERT INTO your_result_table (target_value, lower_bound, upper_bound) VALUES (?, ?, ?) """, (target_num, lower_val, upper_val)) conn.commit() conn.close()
定时触发配置
用系统自带工具实现每小时触发:
- Linux/macOS:配置
cron任务,添加类似0 * * * * python3 /path/to/your_script.py [传入数值]的规则 - Windows:在任务计划程序中创建定时任务,指定脚本路径和参数
内容的提问来源于stack exchange,提问作者CharlesH
相关产品推荐
相关产品推荐

