一張表存儲歷史數據,最多存儲HISTORY_TABLE_MAX_ROWS條數據,當表中數據未達到HISTORY_TABLE_MAX_ROWS,直接插入;如果達到的話需要保證插入新數據的時候將最舊的數據刪除
這里使用先update最新數據,然后再重新update全表的id號-1嗎,,這樣就能實現這個功能了。
def update_history_db(conn, cur, param , HISTORY_TABLE_MAX_ROWS, table_name):# 注意,這里的conn和cur不是函數內部分配的select_sql = "SELECT id from %s order by id desc limit 1" % table_nameselect_sql_id = "SELECT id from %s order by id limit 1" % table_nameinsert_sql = "INSERT into %s values(0, %s)" % (table_name, param)update_sql_id = "UPDATE %s SET id = id - 1 " % table_nametry:# 首先判斷一下表單行數有沒有超過閾值result = SELECT(conn, cur, select_sql)rows = 0for row in result:rows = row[0]if rows < HISTORY_TABLE_MAX_ROWS:INSERT(conn, cur, insert_sql)else:# 首先獲取最小的idresult = SELECT(conn, cur, select_sql_id)min_id = 1for row in result:min_id = row[0]update_sql = "UPDATE %s SET id = %s, param = %s where id = %s" % (table_name, (HISTORY_TABLE_MAX_ROWS + 1), param)UPDATE(conn, cur, update_sql)# 然后更新id自減1UPDATE(conn, cur, update_sql_id)except BaseException:logging.critical("Function: update_all_nums_history_db stop ...")return