在数据库表中,如果特定行之前已被修改或更新,我希望该行不被更改或不能被修改,假设我在 5 秒内设置,即使程序试图修改该行,然后该行可以再次修改或更新。这可能吗?
我还没有尝试任何东西,因为我不知道是否可能
是的,这是可能的。要实现这种行为,您可以在表中添加一个新列,我们称之为
last_modified
。其中获取当前时间戳的默认值
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()
代码目前未经测试,但我希望你能理解