在SQLite3 python中,如果一行之前已经更新过,那么它可能在5秒内无法更新吗

acruukt9  于 2023-05-18  发布在  SQLite
关注(0)|答案(1)|浏览(146)

在一个数据库表中,如果一个特定的行以前被修改或更新,我希望该行不被更改或不能被修改,比方说我在5秒内设置,即使程序试图修改该行,然后在那之后该行可以被修改或更新一次。这可能吗?
我还没有尝试任何东西,因为我不知道这是否可能

dm7nw8vv

dm7nw8vv1#

是的,这是可能的。要实现这种行为,您可以向表中添加一个新列,我们称之为last_modified。其中get是当前时间戳的默认值

CREATE TABLE your_table (
    ...
    last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

ALTER TABLE your_table ADD COLUMN last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

现在,每次要更新表时,都要检查受影响的行在过去5秒内是否已更新,如果没有,则更新该行,如果是,则通过错误进行更新。

import sqlite3
import time

# Connect to the SQLite database
conn = sqlite3.connect('your_database.db')
cursor = conn.cursor()

# Create the table if it doesn't exist
cursor.execute('''CREATE TABLE IF NOT EXISTS your_table
                  (id INTEGER PRIMARY KEY AUTOINCREMENT,
                   column1 TEXT,
                   column2 TEXT,
                   last_modified TIMESTAMP DEFAULT CURRENT_TIMESTAMP)''')

# Function to check if a row can be modified
def can_modify_row(row_id, interval):
    cursor.execute("SELECT ROUND((JULIANDAY('now') - JULIANDAY(last_modified)) * 86400) FROM your_table WHERE id = ?", (row_id,))
    elapsed_time = cursor.fetchone()[0]
    return elapsed_time > interval

# Update a row, setting the last_modified timestamp to the current time
def update_row(row_id, column1_value, column2_value):
    cursor.execute("UPDATE your_table SET column1 = ?, column2 = ?, last_modified = CURRENT_TIMESTAMP WHERE id = ?", (column1_value, column2_value, row_id))
    conn.commit()

# Example usage
row_id = 1
interval = 5  # seconds

if can_modify_row(row_id, interval):
    print("Modifying the row...")
    update_row(row_id, "new_value1", "new_value2")
else:
    print("Cannot modify the row yet. Please try again later.")

# Close the database connection
conn.close()

该代码目前尚未测试,但我希望你得到的想法

相关问题