You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

AWS Lambda执行成功但未更新RDS PostgreSQL表问题

问题分析与解决方案

核心问题原因

你的问题本质是事务未提交:

  • SQLAlchemy通过engine.connect()建立的连接默认会开启事务,且不会自动提交。Lambda执行插入操作后,事务处于未提交状态,只有当前连接能看到这条未提交的行(所以Lambda里查得到),但其他外部连接(本地pgAdmin/代码)看不到。
  • PostgreSQL的主键自增序列在执行插入语句时就会被消耗,哪怕事务最终没提交,所以本地后续插入会跳过被占用的ID(比如跳过26)。

解决方法

你可以通过以下几种方式修复:

1. 手动提交事务

在插入操作后显式调用commit(),然后再关闭连接:

from sqlalchemy import create_engine, text

engine = create_engine("postgresql://%s:%s@%s:%s/%s" % (username, password, host, port, database))
conn = engine.connect()
print("CONNECTED TO RDS")

# 查询现有数据
query = 'select * from predictions'
result = conn.execute(text(query)).fetchall()
print("THE QUERY RESULT IS", '\n', result)

# 执行插入并提交
upload_query = "INSERT INTO predictions (image_url, image_class) VALUES ('LOCAL_ADD', 'LOCAL_ADD');"
conn.execute(text(upload_query))
conn.commit()  # 关键:提交事务

# 再次查询验证
query = 'select * from predictions'
result = conn.execute(text(query)).fetchall()
print("THE QUERY RESULT IS", '\n', result)

conn.close()

2. 使用自动提交模式创建连接

创建连接时指定autocommit=True,这样每个语句执行后都会自动提交:

engine = create_engine("postgresql://%s:%s@%s:%s/%s" % (username, password, host, port, database))
conn = engine.connect(execution_options={"autocommit": True})  # 开启自动提交

3. 使用上下文管理器(推荐)

用with语句管理连接和事务,它会自动处理提交或异常回滚:

from sqlalchemy import create_engine, text

engine = create_engine("postgresql://%s:%s@%s:%s/%s" % (username, password, host, port, database))

with engine.connect() as conn:
    print("CONNECTED TO RDS")
    
    query = 'select * from predictions'
    result = conn.execute(text(query)).fetchall()
    print("THE QUERY RESULT IS", '\n', result)
    
    upload_query = "INSERT INTO predictions (image_url, image_class) VALUES ('LOCAL_ADD', 'LOCAL_ADD');"
    conn.execute(text(upload_query))
    
    conn.commit()  # 或者在with块结束前提交
    
    query = 'select * from predictions'
    result = conn.execute(text(query)).fetchall()
    print("THE QUERY RESULT IS", '\n', result)
# with块结束后自动关闭连接

额外验证点

  • 检查Lambda的CloudWatch日志,确认commit()语句正常执行,没有抛出异常。
  • 你的RDS安全组配置没问题(Lambda能正常连接查询),所以不用纠结网络权限问题。

内容的提问来源于stack exchange,提问作者Hrushi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 20:44:55