Programmatically Working With Our DynamoDB Table
Code snippets for this tutorial:
import boto3
# Initialize a DynamoDB client
dynamodb = boto3.resource('dynamodb')
# represent table in Python
table = dynamodb.Table('customer-accounts')
# sample customer
customer = {
'customer_id': 1010,
'join_date': '2024-06-04',
'name': 'Patsy Smith',
'age': 38
}
# add customer to table
try:
table.put_item(Item=customer)
print("Result: Customer added successfully.")
except Exception as e:
print(f"Result: Failed to add customer: {str(e)}")
Code snippets for this tutorial:
import boto3
# Initialize a DynamoDB client
dynamodb = boto3.resource('dynamodb')
# represent table in Python
table = dynamodb.Table('customer-accounts')
# count table records using scan (be careful when table is large)
response = table.scan(Select='COUNT')
print(response['Count'])
# return all records using scan (be careful when table is large)
response = table.scan()
for item in response['Items']:
print(item)
# retrieve results using "query"
response = table.query(KeyConditionExpression='customer_id = :id AND join_date = :date',
ExpressionAttributeValues={':id': 1010, ':date': '2024-06-04'})
for item in response['Items']:
print(item)
# retrieve results using "scan"
response = table.scan(FilterExpression='age > :age',
ExpressionAttributeValues={':age': 30})
for item in response['Items']:
print(item)
#########################################################################
# IMPORTANT - DELETE OUR TABLE !!
#########################################################################
try:
table.delete()
print("Deletion of table has started")
table.wait_until_not_exists()
print("Deletion of table has finished")
except Exception as e:
print(f"Error deleting table: {e}")
0 comments