如何使用 Lambda 函数截断和加载 RDS(SQL 服务器)中的数据

How to truncate and load data in RDS (SQL Server) using Lambda function

我需要在删除之前加载的table内容后将数据加载到RDS(SQL服务器)。那是因为我不想附加 table 内容。我想使用 Lambda 函数来实现。

这是我的示例 Lambda 函数脚本:

import pyodbc
import pandas as pd
# insert data from csv file into dataframe(df).
server = 'yourservername' 
database = 'AdventureWorks' 
username = 'username' 
password = 'yourpassword' 
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
# Insert Dataframe into SQL Server:
for index, row in df.iterrows():
     cursor.execute("INSERT INTO HumanResources.DepartmentTest (DepartmentID,Name,GroupName) values(?,?,?)", row.DepartmentID, row.Name, row.GroupName)
cnxn.commit()
cursor.close()

我尝试在“insert”命令之前执行以下命令

for index, row in df.iterrows():
cursor.execute("truncate table HumanResources.DepartmentTest")

不幸的是,它没有正常工作。虽然我的 table 是 t运行cated 但只插入了一行。不知道为什么!

谁能告诉我为什么只加载了一行?我试图通过 S3 存储桶加载的 csv 文件中有超过 50k 行。如果我 运行 我的 cursor.execute 单独工作。

如有任何帮助,我们将不胜感激。

我找到了实现我之前尝试的目标的解决方案。要在截断旧的 table 内容后加载数据,我需要从 "for index, row in df.iterrows():" 中删除 cursor.execute("truncate table HumanResources.DepartmentTest") 并将其放在下面;

cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER='+server+';DATABASE='+database+';UID='+username+';PWD='+ password)
cursor = cnxn.cursor()
cursor.execute("truncate table HumanResources.DepartmentTest")