Python中的sqlite3
我该如何检查数据库文件是否已经存在?如果存在的话,我又该如何检查里面是否已经有一个特定的表呢?
1 个回答
10
要检查一个数据库是否存在,你可以用 sqlite3.connect
连接到你认为包含数据库的文件,然后尝试在上面运行一个查询。如果这个文件 不是 数据库,你会看到这个错误:
>>> c.execute("SELECT * FROM tbl")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
sqlite3.DatabaseError: file is encrypted or is not a database
sqlite3.connect
如果数据库不存在,它会自动创建一个;正如 @johnp 在评论中提到的,os.path.exists
可以告诉你这个文件是否存在。
要检查是否有现有的表,你可以 查询 sqlite_master。比如:
>>> def foo(name):
... for row in c.execute("SELECT name FROM sqlite_master WHERE type='table'"):
... if row == (name,):
... return True
... return False
...
>>> foo("tz_data")
True
>>> foo("asdf")
False