【问题标题】:sqlite3 in PythonPython中的sqlite3
【发布时间】:2009-10-04 14:13:24
【问题描述】:

如何检查数据库文件是否已经存在? 而且,如果它存在,我如何检查它是否已经有一个特定的表?

【问题讨论】:

标签: python sqlite


【解决方案1】:

要查看数据库是否存在,您可以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 在 cmets 中指出的那样,os.path.exists 会告诉您该文件是否存在。

要检查现有表,请query against 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

【讨论】:

  • hmm... 调用 sqlite3.connect() 会自动创建数据库吗?
  • 如果要查看文件是否存在,请使用 os.path.exists(): import os.path os.path.exists('dbname.db') 在 sqlite3 之前执行此检查。 connect() 以避免在数据库不存在时创建数据库。
  • 抱歉——在 cmets 中格式化代码不太顺利,但你应该明白了。
猜你喜欢
  • 1970-01-01
  • 2020-06-27
  • 2015-05-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-25
相关资源
最近更新 更多