This article will discuss in detail how to connect to all types of databases in Python and implement corresponding CRUD (create, read, update, delete) operations. We will analyze the methods of connecting MySQL, SQL Server, Oracle, PostgreSQL, MongoDB, SQLite, DB2, Redis, Cassandra, Microsoft Access, ElasticSearch, Neo4j, InfluxDB, Snowflake, Amazon DynamoDB, Microsoft Azure CosMos DB database one by one, and demonstrate the corresponding CRUD operations.
MySQL
Connect to the database
Python can use the mysql-connector-python library to connect to the MySQL database:
import mysql.connector
conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')
print("Opened MySQL database successfully")
conn.close()
CRUD operations
Next, we'll show how to perform basic CRUD operations in MySQL.
Create
conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')
cursor = conn.cursor()
cursor.execute("CREATE TABLE Employees (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE INT, ADDRESS CHAR(50), SALARY REAL)")
print("Table created successfully")
conn.close()
Read (Retrieve)
conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')
cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3])
conn.close()
Update
conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')
cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()
print("Total number of rows updated :", cursor.rowcount)
conn.close()
Delete
conn = mysql.connector.connect(user='username', password='password', host='127.0.0.1', database='my_database')
cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()
print("Total number of rows deleted :", cursor.rowcount)
conn.close()
SQL Server
Connect to the database
Python can use the pyodbc library to connect to the SQL Server database:
import pyodbc
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')
print("Opened SQL Server database successfully")
conn.close()
CRUD operations
Next, we'll show how to perform basic CRUD operations in SQL Server.
Create
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')
cursor = conn.cursor()
cursor.execute("CREATE TABLE Employees (ID INT PRIMARY KEY NOT NULL, NAME VARCHAR(20) NOT NULL, AGE INT, ADDRESS CHAR(50), SALARY REAL)")
conn.commit()
print("Table created successfully")
conn.close()
Read (Retrieve)
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')
cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3])
conn.close()
Update
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')
cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()
print("Total number of rows updated :", cursor.rowcount)
conn.close()
Delete
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=localhost;DATABASE=my_database;UID=username;PWD=password')
cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()
print("Total number of rows deleted :", cursor.rowcount)
conn.close()
Oracle
Connect to the database
Python can use the cx_Oracle library to connect to the Oracle database:
import cx_Oracle
dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
print("Opened Oracle database successfully")
conn.close()
CRUD operations
Next, we'll show how to perform basic CRUD operations in Oracle.
Create
dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
cursor = conn.cursor()
cursor.execute("CREATE TABLE Employees (ID NUMBER(10) NOT NULL PRIMARY KEY, NAME VARCHAR2(20) NOT NULL, AGE NUMBER(3), ADDRESS CHAR(50), SALARY NUMBER(10, 2))")
conn.commit()
print("Table created successfully")
conn.close()
Read (Retrieve)
dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3])
conn.close()
Update
dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()
print("Total number of rows updated :", cursor.rowcount)
conn.close()
Delete
dsn_tns = cx_Oracle.makedsn('localhost', '1521', service_name='my_database')
conn = cx_Oracle.connect(user='username', password='password', dsn=dsn_tns)
cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()
print("Total number of rows deleted :", cursor.rowcount)
conn.close()
PostgreSQL
Connect to the database
Python can use the psycopg2 library to connect to the PostgreSQL database:
import psycopg2
conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")
print("Opened PostgreSQL database successfully")
conn.close()
CRUD operations
Next, we'll show how to do basic CRUD operations in PostgreSQL.
Create
conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")
cursor = conn.cursor()
cursor.execute('''CREATE TABLE Employees
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
conn.commit()
print("Table created successfully")
conn.close()
Read (Retrieve)
conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")
cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3])
conn.close()
Update
conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")
cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()
print("Total number of rows updated :", cursor.rowcount)
conn.close()
Delete
conn = psycopg2.connect(database="my_database", user="username", password="password", host="127.0.0.1", port="5432")
cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()
print("Total number of rows deleted :", cursor.rowcount)
conn.close()
MongoDB
Connect to the database
Python can use the pymongo library to connect to the MongoDB database:
from pymongo import MongoClient
client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]
print("Opened MongoDB database successfully")
client.close()
CRUD operations
Next, we'll show how to perform basic CRUD operations in MongoDB.
Create
In MongoDB, document creation is usually included in an insert operation:
client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]
employees = db["Employees"]
employee = {"id": "1", "name": "John", "age": "30", "address": "New York", "salary": "1000.00"}
employees.insert_one(employee)
print("Document inserted successfully")
client.close()
Read (Retrieve)
client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]
employees = db["Employees"]
cursor = employees.find()
for document in cursor:
print(document)
client.close()
Update
client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]
employees = db["Employees"]
query = { "id": "1" }
new_values = { "$set": { "salary": "25000.00" } }
employees.update_one(query, new_values)
print("Document updated successfully")
client.close()
Delete
client = MongoClient("mongodb://localhost:27017/")
db = client["my_database"]
employees = db["Employees"]
query = { "id": "1" }
employees.delete_one(query)
print("Document deleted successfully")
client.close()
SQLite
Connect to the database
Python uses the sqlite3 library to connect to the SQLite database:
import sqlite3
conn = sqlite3.connect('my_database.db')
print("Opened SQLite database successfully")
conn.close()
CRUD operations
Next, we'll show how to perform basic CRUD operations in SQLite.
Create
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE Employees
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY REAL);''')
conn.commit()
print("Table created successfully")
conn.close()
Read (Retrieve)
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3])
conn.close()
Update
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()
print("Total number of rows updated :", cursor.rowcount)
conn.close()
Delete
conn = sqlite3.connect('my_database.db')
cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()
print("Total number of rows deleted :", cursor.rowcount)
conn.close()
DB2
Connect to the database
Python can use the ibm_db library to connect to the DB2 database:
import ibm_db
dsn = (
"DRIVER={
{IBM DB2 ODBC DRIVER}};"
"DATABASE=my_database;"
"HOSTNAME=127.0.0.1;"
"PORT=50000;"
"PROTOCOL=TCPIP;"
"UID=username;"
"PWD=password;"
)
conn = ibm_db.connect(dsn, "", "")
print("Opened DB2 database successfully")
ibm_db.close(conn)
CRUD operations
Next, we'll show how to perform basic CRUD operations in DB2.
Create
conn = ibm_db.connect(dsn, "", "")
sql = '''CREATE TABLE Employees
(ID INT PRIMARY KEY NOT NULL,
NAME VARCHAR(20) NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY DECIMAL(9, 2));'''
stmt = ibm_db.exec_immediate(conn, sql)
print("Table created successfully")
ibm_db.close(conn)
Read (Retrieve)
conn = ibm_db.connect(dsn, "", "")
sql = "SELECT id, name, address, salary from Employees"
stmt = ibm_db.exec_immediate(conn, sql)
while ibm_db.fetch_row(stmt):
print("ID = ", ibm_db.result(stmt, "ID"))
print("NAME = ", ibm_db.result(stmt, "NAME"))
print("ADDRESS = ", ibm_db.result(stmt, "ADDRESS"))
print("SALARY = ", ibm_db.result(stmt, "SALARY"))
ibm_db.close(conn)
Update
conn = ibm_db.connect(dsn, "", "")
sql = "UPDATE Employees set SALARY = 25000.00 where ID = 1"
stmt = ibm_db.exec_immediate(conn, sql)
ibm_db.commit(conn)
print("Total number of rows updated :", ibm_db.num_rows(stmt))
ibm_db.close(conn)
Delete
conn = ibm_db.connect(dsn, "", "")
sql = "DELETE from Employees where ID = 1"
stmt = ibm_db.exec_immediate(conn, sql)
ibm_db.commit(conn)
print("Total number of rows deleted :", ibm_db.num_rows(stmt))
ibm_db.close(conn)
Microsoft Access
Connect to the database
Python can use the pyodbc library to connect to Microsoft Access databases:
import pyodbc
conn_str = (
r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};'
r'DBQ=path_to_your_access_file.accdb;'
)
conn = pyodbc.connect(conn_str)
print("Opened Access database successfully")
conn.close()
CRUD operations
Next, we will show how to perform basic CRUD operations in Access.
Create
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute('''CREATE TABLE Employees
(ID INT PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL,
AGE INT NOT NULL,
ADDRESS CHAR(50),
SALARY DECIMAL(9, 2));''')
conn.commit()
print("Table created successfully")
conn.close()
Read (Retrieve)
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute("SELECT id, name, address, salary from Employees")
rows = cursor.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("ADDRESS = ", row[2])
print("SALARY = ", row[3])
conn.close()
Update
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute("UPDATE Employees set SALARY = 25000.00 where ID = 1")
conn.commit()
print("Total number of rows updated :", cursor.rowcount)
conn.close()
Delete
conn = pyodbc.connect(conn_str)
cursor = conn.cursor()
cursor.execute("DELETE from Employees where ID = 1")
conn.commit()
print("Total number of rows deleted :", cursor.rowcount)
conn.close()
Cassandra
Connect to the database
Python can use the cassandra-driver library to connect to the Cassandra database:
from cassandra.cluster import Cluster
cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')
print("Opened Cassandra database successfully")
cluster.shutdown()
CRUD operations
Next, we'll show how to do basic CRUD operations in Cassandra.
Create
cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')
session.execute("""
CREATE TABLE Employees (
id int PRIMARY KEY,
name text,
age int,
address text,
salary decimal
)
""")
print("Table created successfully")
cluster.shutdown()
Read (Retrieve)
cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')
rows = session.execute('SELECT id, name, address, salary FROM Employees')
for row in rows:
print("ID = ", row.id)
print("NAME = ", row.name)
print("ADDRESS = ", row.address)
print("SALARY = ", row.salary)
cluster.shutdown()
Update
cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')
session.execute("UPDATE Employees SET salary = 25000.00 WHERE id = 1")
print("Row updated successfully")
cluster.shutdown()
Delete
cluster = Cluster(['127.0.0.1'])
session = cluster.connect('my_keyspace')
session.execute("DELETE FROM Employees WHERE id = 1")
print("Row deleted successfully")
cluster.shutdown()
Redis
Connect to the database
Python can use the redis-py library to connect to the Redis database:
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
print("Opened Redis database successfully")
CRUD operations
Next, we'll show how to do basic CRUD operations in Redis.
Create
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('employee:1:name', 'John')
r.set('employee:1:age', '30')
r.set('employee:1:address', 'New York')
r.set('employee:1:salary', '1000.00')
print("Keys created successfully")
Read (Retrieve)
r = redis.Redis(host='localhost', port=6379, db=0)
print("NAME = ", r.get('employee:1:name').decode('utf-8'))
print("AGE = ", r.get('employee:1:age').decode('utf-8'))
print("ADDRESS = ", r.get('employee:1:address').decode('utf-8'))
print("SALARY = ", r.get('employee:1:salary').decode('utf-8'))
Update
r = redis.Redis(host='localhost', port=6379, db=0)
r.set('employee:1:salary', '25000.00')
print("Key updated successfully")
Delete
r = redis.Redis(host='localhost', port=6379, db=0)
r.delete('employee:1:name', 'employee:1:age', 'employee:1:address', 'employee:1:salary')
print("Keys deleted successfully")
ElasticSearch
Connect to the database
Python can use the elasticsearch library to connect to the ElasticSearch database:
from elasticsearch import Elasticsearch
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
print("Opened ElasticSearch database successfully")
CRUD operations
Next, we'll show how to do basic CRUD operations in ElasticSearch.
Create
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
employee = {
'name': 'John',
'age': 30,
'address': 'New York',
'salary': 1000.00
}
res = es.index(index='employees', doc_type='employee', id=1, body=employee)
print("Document created successfully")
Read (Retrieve)
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
res = es.get(index='employees', doc_type='employee', id=1)
print("Document details:")
for field, details in res['_source'].items():
print(f"{field.upper()} = ", details)
Update
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
res = es.update(index='employees', doc_type='employee', id=1, body={
'doc': {
'salary': 25000.00
}
})
print("Document updated successfully")
Delete
es = Elasticsearch([{'host': 'localhost', 'port': 9200}])
res = es.delete(index='employees', doc_type='employee', id=1)
print("Document deleted successfully")
Neo4j
Connect to the database
Python can use the neo4j library to connect to the Neo4j database:
from neo4j import GraphDatabase
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
print("Opened Neo4j database successfully")
driver.close()
CRUD operations
Next, we'll show how to do basic CRUD operations in Neo4j.
Create
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
with driver.session() as session:
session.run("CREATE (:Employee {id: 1, name: 'John', age: 30, address: 'New York', salary: 1000.00})")
print("Node created successfully")
driver.close()
Read (Retrieve)
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
with driver.session() as session:
result = session.run("MATCH (n:Employee) WHERE n.id = 1 RETURN n")
for record in result:
print("ID = ", record["n"]["id"])
print("NAME = ", record["n"]["name"])
print("ADDRESS = ", record["n"]["address"])
print("SALARY = ", record["n"]["salary"])
driver.close()
Update
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
with driver.session() as session:
session.run("MATCH (n:Employee) WHERE n.id = 1 SET n.salary = 25000.00")
print("Node updated successfully")
driver.close()
Delete
driver = GraphDatabase.driver("bolt://localhost:7687", auth=("neo4j", "password"))
with driver.session() as session:
session.run("MATCH (n:Employee) WHERE n.id = 1 DETACH DELETE n")
print("Node deleted successfully")
driver.close()
InfluxDB
Connect to the database
Python can use the InfluxDB-Python library to connect to the InfluxDB database:
from influxdb import InfluxDBClient
client = InfluxDBClient(host='localhost', port=8086)
print("Opened InfluxDB database successfully")
client.close()
CRUD operations
Next, we'll show how to do basic CRUD operations in InfluxDB.
Create
client = InfluxDBClient(host='localhost', port=8086)
json_body = [
{
"measurement": "employees",
"tags": {
"id": "1"
},
"fields": {
"name": "John",
"age": 30,
"address": "New York",
"salary": 1000.00
}
}
]
client.write_points(json_body)
print("Point created successfully")
client.close()
Read (Retrieve)
client = InfluxDBClient(host='localhost', port=8086)
result = client.query('SELECT "name", "age", "address", "salary" FROM "employees"')
for point in result.get_points():
print("ID = ", point['id'])
print("NAME = ", point['name'])
print("AGE = ", point['age'])
print("ADDRESS = ", point['address'])
print("SALARY = ", point['salary'])
client.close()
Update
InfluxDB's data model is different from other databases, it does not have update operations. But you can achieve something like an update operation by writing to the same data point (i.e. with the same timestamp and label) and changing the field value.
Delete
Likewise, InfluxDB does not provide an operation to delete individual data points. However, you can delete an entire series (i.e. table) or delete data for a certain period of time.
client = InfluxDBClient(host='localhost', port=8086)
# 删除整个系列
client.query('DROP SERIES FROM "employees"')
# 删除某个时间段的数据
# client.query('DELETE FROM "employees" WHERE time < now() - 1d')
print("Series deleted successfully")
client.close()
Snowflake
Connect to the database
Python can use the snowflake-connector-python library to connect to the Snowflake database:
from snowflake.connector import connect
con = connect(
user='username',
password='password',
account='account_url',
warehouse='warehouse',
database='database',
schema='schema'
)
print("Opened Snowflake database successfully")
con.close()
CRUD operations
Next, we'll show how to do basic CRUD operations in Snowflake.
Create
con = connect(
user='username',
password='password',
account='account_url',
warehouse='warehouse',
database='database',
schema='schema'
)
cur = con.cursor()
cur.execute("""
CREATE TABLE EMPLOYEES (
ID INT,
NAME STRING,
AGE INT,
ADDRESS STRING,
SALARY FLOAT
)
""")
cur.execute("""
INSERT INTO EMPLOYEES (ID, NAME, AGE, ADDRESS, SALARY) VALUES
(1, 'John', 30, 'New York', 1000.00)
""")
print("Table created and row inserted successfully")
con.close()
Read (Retrieve)
con = connect(
user='username',
password='password',
account='account_url',
warehouse='warehouse',
database='database',
schema='schema'
)
cur = con.cursor()
cur.execute("SELECT * FROM EMPLOYEES WHERE ID = 1")
rows = cur.fetchall()
for row in rows:
print("ID = ", row[0])
print("NAME = ", row[1])
print("AGE = ", row[2])
print("ADDRESS = ", row[3])
print("SALARY = ", row[4])
con.close()
Update
con = connect(
user='username',
password='password',
account='account_url',
warehouse='warehouse',
database='database',
schema='schema'
)
cur = con.cursor()
cur.execute("UPDATE EMPLOYEES SET SALARY = 25000.00 WHERE ID = 1")
print("Row updated successfully")
con.close()
Delete
con = connect(
user='username',
password='password',
account='account_url',
warehouse='warehouse',
database='database',
schema='schema'
)
cur = con.cursor()
cur.execute("DELETE FROM EMPLOYEES WHERE ID = 1")
print("Row deleted successfully")
con.close()
Amazon DynamoDB
Connect to the database
Python can use the boto3 library to connect to Amazon DynamoDB:
import boto3
dynamodb = boto3.resource('dynamodb', region_name='us-west-2',
aws_access_key_id='Your AWS Access Key',
aws_secret_access_key='Your AWS Secret Key')
print("Opened DynamoDB successfully")
CRUD operations
Next, we'll show how to do basic CRUD operations in DynamoDB.
Create
table = dynamodb.create_table(
TableName='Employees',
KeySchema=[
{
'AttributeName': 'id',
'KeyType': 'HASH'
},
],
AttributeDefinitions=[
{
'AttributeName': 'id',
'AttributeType': 'N'
},
],
ProvisionedThroughput={
'ReadCapacityUnits': 5,
'WriteCapacityUnits': 5
}
)
table.put_item(
Item={
'id': 1,
'name': 'John',
'age': 30,
'address': 'New York',
'salary': 1000.00
}
)
print("Table created and item inserted successfully")
Read (Retrieve)
table = dynamodb.Table('Employees')
response = table.get_item(
Key={
'id': 1,
}
)
item = response['Item']
print(item)
Update
table = dynamodb.Table('Employees')
table.update_item(
Key={
'id': 1,
},
UpdateExpression='SET salary = :val1',
ExpressionAttributeValues={
':val1': 25000.00
}
)
print("Item updated successfully")
Delete
table = dynamodb.Table('Employees')
table.delete_item(
Key={
'id': 1,
}
)
print("Item deleted successfully")
Microsoft Azure CosMos DB
Connect to the database
Python can use the azure-cosmos library to connect to Microsoft Azure CosMos DB:
from azure.cosmos import CosmosClient, PartitionKey, exceptions
url = 'Cosmos DB Account URL'
key = 'Cosmos DB Account Key'
client = CosmosClient(url, credential=key)
database_name = 'testDB'
database = client.get_database_client(database_name)
container_name = 'Employees'
container = database.get_container_client(container_name)
print("Opened CosMos DB successfully")
CRUD operations
Next, we will show how to perform basic CRUD operations in CosMos DB.
Create
database = client.create_database_if_not_exists(id=database_name)
container = database.create_container_if_not_exists(
id=container_name,
partition_key=PartitionKey(path="/id"),
offer_throughput=400
)
container.upsert_item({
'id': '1',
'name': 'John',
'age': 30,
'address': 'New York',
'salary': 1000.00
})
print("Container created and item upserted successfully")
Read (Retrieve)
for item in container.read_all_items():
print(item)
Update
for item in container.read_all_items():
if item['id'] == '1':
item['salary'] = 25000.00
container.upsert_item(item)
print("Item updated successfully")
Delete
for item in container.read_all_items():
if item['id'] == '1':
container.delete_item(item, partition_key='1')
print("Item deleted successfully")
If it is helpful, please pay more attention to the personal WeChat public account: [Python full perspective] TeahLead_KrisChang, 10+ years of experience in the Internet and artificial intelligence industry, 10+ years of experience in technology and business team management, Tongji Software Engineering Bachelor, Fudan Engineering Management Master, Aliyun certified cloud service senior architect, head of AI product business with hundreds of millions of revenue.