[英]insert multiple items into DynamoDB table using .NET
我必须将至少 3 个用户凭据(用户名、密码)存储到 DynamoDB 表中,但我找不到如何使用此代码创建和存储多个用户凭据。 我使用此代码只创建了一个凭据,我的目标是将多个凭据添加到我创建的同一个表中。 先感谢您。
public async void InsertItem()
{
PutItemRequest request = new PutItemRequest
{
TableName = tableName,
Item = new Dictionary<string, AttributeValue>
{
{"Username", new AttributeValue{S="jake@hotmail.com"} },
{"Password", new AttributeValue{S="1234"} }
}
};
try
{
var response = await client.PutItemAsync(request);
if (response.HttpStatusCode == System.Net.HttpStatusCode.OK) MessageBox.Show("Item added successfully!");
}
catch (InternalServerErrorException iee)
{
MessageBox.Show("An error occurred on the server side" + iee.Message);
}
catch (ResourceNotFoundException ex)
{
MessageBox.Show("The operation tried to access a nonexistent table or index.");
}
}
public async void GetItem()
{
GetItemRequest request = new GetItemRequest
{
TableName = tableName,
Key = new Dictionary<string, AttributeValue>
{
{"Username", new AttributeValue{S="jake@hotmail.com"} },
{"Password", new AttributeValue{S="1234"} }
}
};
try
{
var response = await client.GetItemAsync(request);
if(response.HttpStatusCode == System.Net.HttpStatusCode.OK)
{
if (response.Item.Count > 0)
{
MessageBox.Show("Item(s) retrieved successfully");
foreach (var item in response.Item) ;
}
}
}
catch (InternalServerErrorException iee)
{
MessageBox.Show("An error occurred on the server side" + iee.Message);
}
catch (ResourceNotFoundException ex)
{
MessageBox.Show("The operation tried to access a nonexistent table or index.");
}
}
首先,如果这是一个演示项目,没关系,但不要随时随地为数据库中的任何人存储任何未经哈希处理的密码——用户数据的安全是第一要务。
有关详细信息,请参阅OWASP 的密码存储备忘单。
更改InsertItem()
和GetItem()
以接受username
和password
的 2 个string
参数,这将允许您重用该方法。
还要更改Dictionary<string, AttributeValue>
中的硬编码用户名和密码值以使用您的参数:
public async void 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 } }
}
};
...
然后使用不同的用户名和密码多次调用InsertItem()
以插入多个项目。
如果您只是添加 3 个用户,这很好,但如果您经常对数据库进行批量写入,请查看BatchWriteItem
方法,它会更快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.