Skip to main content
 首页 » 编程设计

python之如何检查数据库是否已经存在

2025年05月04日33bjzhanghao

我正在编写一个将一些文档加载到 couchdb 中的小型 Python 程序。 检查具有特定名称的数据库是否已经存在会非常方便,因此我可以创建一个新数据库或打开现有数据库。我想要做的是这样的:

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) 

我知道 try-except block 可以解决问题,但有没有更优雅的方法?

请您参考如下方法:

我能想到的最简单的方法是:

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

如果同名数据库存在则返回True,否则返回False

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