fix: 数据库insert方法使用INSERT OR REPLACE更新已存在记录

This commit is contained in:
2025-12-29 04:57:21 +08:00
parent 152904a38c
commit 272d0156bb

View File

@@ -108,31 +108,20 @@ class DailyLogsDatabase:
self.conn.commit()
def insert(self, log: Dict) -> bool:
"""插入记录(存在则跳过,不存在则插入)"""
"""插入记录(存在则替换,不存在则插入)"""
try:
cursor = self.conn.cursor()
# 检查是否已存在
# 使用 INSERT OR REPLACE 来更新已存在的记录
cursor.execute('''
SELECT id FROM daily_handover_logs
WHERE date = ? AND shift = ? AND ship_name = ?
''', (log['date'], log['shift'], log['ship_name']))
existing = cursor.fetchone()
if existing:
# 记录已存在,跳过
return False
else:
# 插入新记录
cursor.execute('''
INSERT INTO daily_handover_logs
(date, shift, ship_name, teu, efficiency, vehicles, created_at)
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
''', (
log['date'], log['shift'], log['ship_name'],
log.get('teu'), log.get('efficiency'), log.get('vehicles')
))
self.conn.commit()
return True
INSERT OR REPLACE INTO daily_handover_logs
(date, shift, ship_name, teu, efficiency, vehicles, created_at)
VALUES (?, ?, ?, ?, ?, ?, CURRENT_TIMESTAMP)
''', (
log['date'], log['shift'], log['ship_name'],
log.get('teu'), log.get('efficiency'), log.get('vehicles')
))
self.conn.commit()
return True
except sqlite3.Error as e:
print(f"数据库错误: {e}")
return False