How to check if database already exists

放肆的年华 提交于 2019-12-24 17:07:08

问题


I am writing a small Python program that loads some documents into couchdb. It would be very convenient to check whether a database with a certain name already exists, so I can either create a new one or open the existing one. What I want to do is something like this:

import couchdb

def connect(url, dbName):
    server = couchdb.Server(url)
    if dbName exists: # how do I do this?
        return server[dbName]
    else:
        return server.create(dbName)

I know a try-except block would do the trick, but isn't there a more elegant way?


回答1:


The easiest way I can think is:

import couchdb
server = couchdb.Server("http://localhost:5984")
"dataBaseName" in server

Return True if a database with the name exists, False otherwise

https://github.com/djc/couchdb-python/blob/master/couchdb/client.py#L90-L101




回答2:


You can do something like:

try:
    couch = couchdb.Server() # assuming localhost
    db = couch['existent']
except:
    db = couch.create('somedb')


来源:https://stackoverflow.com/questions/35465360/how-to-check-if-database-already-exists

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!