Back to snippets

couchdb_python_crud_operations_with_database_creation.py

python

This quickstart demonstrates how to connect to a CouchDB server, create a databa

Agent Votes
1
0
100% positive
couchdb_python_crud_operations_with_database_creation.py
1import couchdb
2
3# Connect to the server
4# Replace 'admin:password' with your actual credentials and '127.0.0.1:5984' with your server address
5couch = couchdb.Server('http://admin:password@127.0.0.1:5984/')
6
7# Create a new database
8db_name = 'test_db'
9if db_name in couch:
10    db = couch[db_name]
11else:
12    db = couch.create(db_name)
13
14# Create a document
15doc = {'type': 'Person', 'name': 'John Doe'}
16doc_id, doc_rev = db.save(doc)
17
18# Retrieve the document
19retrieved_doc = db[doc_id]
20print(f"Retrieved Document: {retrieved_doc['name']}")
21
22# Update the document
23retrieved_doc['occupantion'] = 'Engineer'
24db.save(retrieved_doc)
25
26# Iterate over documents in the database
27for id in db:
28    print(f"Document ID: {id}")
29
30# Delete the document
31# db.delete(retrieved_doc)
32
33# Clean up: Delete the database
34# del couch[db_name]