Python中的sqlite3 [英] sqlite3 in Python

查看:52
本文介绍了Python中的sqlite3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

解决方案

要查看数据库是否存在,可以sqlite3.connect 到您认为包含数据库的文件,并尝试对其运行查询.如果它不是一个数据库,你会得到这个错误:

<预><代码>>>>c.execute("SELECT * FROM tbl")回溯(最近一次调用最后一次):文件<stdin>",第 1 行,在 <module> 中sqlite3.DatabaseError:文件已加密或不是数据库

sqlite3.connect 创建数据库,如果它不存在;正如@johnp 在评论中指出的那样,os.path.exists 会告诉你文件是否存在.

要检查现有表,您可以查询 sqlite_master.例如:

<预><代码>>>>定义 foo(名称):...对于 c.execute("SELECT name FROM sqlite_master WHERE type='table'") 中的行:...如果行==(名称,):...返回真...返回假...>>>foo("tz_data")真>>>foo("asdf")假的

How do I check if the database file already exists or not? And, if the it exists, how do I check if it already has a specific table or not?

解决方案

To see if a database exists, you can sqlite3.connect to the file that you think contains the database, and try running a query on it. If it is not a database, you will get this error:

>>> 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 will create the database if it doesn't exist; as @johnp points out in the comments, os.path.exists will tell you whether the file exists.

To check for existing tables, you query against sqlite_master. For example:

>>> 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

这篇关于Python中的sqlite3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆