SoFunction
Updated on 2024-10-26

Python operation CouchDB database simple example

Install the python couchDb library:

/pypi/CouchDB/0.10

Connecting to the server

Copy Code The code is as follows.

>>> import couchdb
>>> couch = (':5984/')

Creating a database
Copy Code The code is as follows.

>>> db = ('test') # create a new database
>>> db = couch['mydb'] # Use an already existing database

Create a document and insert it into the database:
Copy Code The code is as follows.

>>> doc = {'foo': 'bar'}
>>> (doc)
('e0658cab843b59e63c8779a9a5000b01', '1-4c6114c65e295552ab1019e2b046b10e')
>>> doc
{'_rev': '1-4c6114c65e295552ab1019e2b046b10e', 'foo': 'bar', '_id': 'e0658cab843b59e63c8779a9a5000b01'}

The save() method returns the '_id','_rev' fields
Query database by id
Copy Code The code is as follows.

>>> db['e0658cab843b59e63c8779a9a5000b01']
<Document 'e0658cab843b59e63c8779a9a5000b01'@'1-4c6114c65e295552ab1019e2b046b10e' {'foo': 'bar'}>

Update the documentation :
Copy Code The code is as follows.

>>> data = db["5fecc0d7fe5acac6b46359b5eec4f3ff"]   
>>> data['billSeconds'] = 191
>>> (data)
(u'5fecc0d7fe5acac6b46359b5eec4f3ff', u'3-6b8a6bb9f2428c510dcacdd5c918d632')

Traversing the database
Copy Code The code is as follows.

>>> for id in db:
...     print id
...
'e0658cab843b59e63c8779a9a5000b01'

Delete documents and clean up the database
Copy Code The code is as follows.

>>> (doc)
>>> ('test')