Python中的sqlite3
问题内容:
如何检查数据库文件是否已经存在?并且,如果它存在,我如何检查它是否已经有一个特定的表?
问题答案:
若要查看数据库是否存在,可以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