使用.NET向DynamoDB表批量插入多条用户凭证的实现问题
解决方案
你可以通过两种方式实现多条用户凭证插入,以下是可直接使用的代码示例:
方案1:改造现有单条插入方法,灵活传入用户信息
先把写死的插入方法改成可接收用户名、密码参数的通用方法,循环调用即可插入多条,适合少量数据插入场景:
// 改造后的通用插入方法,注意将async void改为async Task,避免异步异常无法捕获 public async Task InsertItem(string username, string password) { PutItemRequest request = new PutItemRequest { TableName = tableName, Item = new Dictionary<string, AttributeValue> { {"Username", new AttributeValue{S= username} }, {"Password", new AttributeValue{S= password} } } }; try { var response = await client.PutItemAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) MessageBox.Show($"用户 {username} 凭证添加成功!"); } catch (InternalServerErrorException iee) { MessageBox.Show("服务端发生错误: " + iee.Message); } catch (ResourceNotFoundException ex) { MessageBox.Show("操作访问的表或索引不存在: " + ex.Message); } } // 调用示例:插入3组凭证 public async Task BatchInsertUsers() { // 定义要插入的3组用户凭证 var userList = new List<(string Username, string Password)> { ("jake@hotmail.com", "1234"), ("rose@hotmail.com", "5678"), ("tom@hotmail.com", "9012") }; foreach (var user in userList) { await InsertItem(user.Username, user.Password); } MessageBox.Show("所有用户凭证插入完成"); }
方案2:使用BatchWriteItemAsync批量写入接口
一次性提交多条写入请求,减少网络请求次数,效率更高,单批次最多支持插入25条数据:
public async Task BatchInsertUsers() { var request = new BatchWriteItemRequest { RequestItems = new Dictionary<string, List<WriteRequest>> { { tableName, new List<WriteRequest> { new WriteRequest(new PutRequest { Item = new Dictionary<string, AttributeValue> { {"Username", new AttributeValue{S= "jake@hotmail.com"} }, {"Password", new AttributeValue{S= "1234"} } } }), new WriteRequest(new PutRequest { Item = new Dictionary<string, AttributeValue> { {"Username", new AttributeValue{S= "rose@hotmail.com"} }, {"Password", new AttributeValue{S= "5678"} } } }), new WriteRequest(new PutRequest { Item = new Dictionary<string, AttributeValue> { {"Username", new AttributeValue{S= "tom@hotmail.com"} }, {"Password", new AttributeValue{S= "9012"} } } }) } } } }; try { var response = await client.BatchWriteItemAsync(request); if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) { MessageBox.Show("3组用户凭证批量插入成功"); } } catch (Exception ex) { MessageBox.Show("批量插入失败: " + ex.Message); } }
补充提示
你现有代码中的GetItem方法同时将Username和Password作为主键查询,需要确认你的DynamoDB表设置的是复合主键(分区键Username + 排序键Password),如果仅Username为分区键,不需要在查询条件中传入Password,否则会触发查询错误。
内容的提问来源于stack exchange,提问作者moony
相关产品推荐
相关产品推荐

