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

遍历pandas DataFrame向AWS RDS插入数据时出现tuple属性错误如何解决?

错误根因

df.iterrows() 遍历返回的每个元素是长度为2的元组,结构为 (行索引, 行数据Series对象),你没有解构这个元组,直接把整个元组当作row使用,自然会报tuple没有user_id属性的错误。同时原代码中cursor.execute的语法存在疏漏,SQL语句和参数之间缺少分隔逗号,参数也未按要求封装为元组格式。

修正后可用代码

mycsv = client.get_object(Bucket = aml_bucket, Key = file_name)
bc_body = mycsv['Body']
csv_string = bc_body.read().decode('utf-8')
df = pd.read_csv(StringIO(csv_string))
# 解构iterrows返回的元组,分别获取行索引和行数据
for idx, row in df.iterrows():
  cursor.execute('''insert into new_table(user_id, first_name)
  VALUES(?,?)''',
  (row.user_id,
  row.first_name))
# 非自动提交场景需要手动执行事务提交,根据你使用的数据库驱动调整
# conn.commit()

可选优化建议

逐行插入性能很低,数据量较大时容易触发Lambda超时,推荐使用批量插入减少数据库交互次数:

# 批量生成参数列表
params = [(row.user_id, row.first_name) for _, row in df.iterrows()]
cursor.executemany('insert into new_table(user_id, first_name) VALUES(?,?)', params)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 11:57:06