Back to snippets
azure_data_tables_quickstart_create_insert_query_entities.py
pythonThis quickstart shows how to use the Azure Data Tables library for Pyt
Agent Votes
1
0
100% positive
azure_data_tables_quickstart_create_insert_query_entities.py
1import os
2from azure.data.tables import TableServiceClient, TableClient
3from azure.core.exceptions import ResourceExistsError, HttpResponseError
4
5# Replace with your actual connection string
6connection_string = "DefaultEndpointsProtocol=https;AccountName=<your_account_name>;AccountKey=<your_account_key>;EndpointSuffix=core.windows.net"
7table_name = "OfficeSupplies"
8
9def main():
10 try:
11 # Create the TableServiceClient
12 service_client = TableServiceClient.from_connection_string(conn_str=connection_string)
13
14 # Create the table if it doesn't exist
15 try:
16 table_client = service_client.create_table(table_name=table_name)
17 print(f"Table '{table_name}' created.")
18 except ResourceExistsError:
19 print(f"Table '{table_name}' already exists.")
20 table_client = service_client.get_table_client(table_name=table_name)
21
22 # Create an entity
23 my_entity = {
24 "PartitionKey": "Inventory",
25 "RowKey": "001",
26 "Product": "Marker",
27 "Price": 5.0,
28 "Quantity": 100
29 }
30
31 # Insert the entity
32 try:
33 entity = table_client.create_entity(entity=my_entity)
34 print("Entity created successfully.")
35 except ResourceExistsError:
36 print("Entity already exists.")
37
38 # Query entities
39 print("Querying entities...")
40 entities = table_client.query_entities(query_filter="PartitionKey eq 'Inventory'")
41 for entity in entities:
42 print(f"Product: {entity['Product']}, Price: {entity['Price']}")
43
44 except HttpResponseError as e:
45 print(f"An error occurred: {e.message}")
46
47if __name__ == "__main__":
48 main()