在Python程序中使用SQLite [英] Using SQLite in a Python program
问题描述
尝试做的是进行方法检查以查看数据库是否已经创建。如果是这样,那么我可以使用它。如果没有,则引发异常,程序将创建数据库。 (或使用if / else语句,以较大者为准)。
我创建了一个测试脚本来查看我的逻辑是否正确,但它不工作。当我创建try语句时,它只创建一个新的数据库,而不是检查是否已经存在。下次运行脚本时,即使我尝试捕获异常,我也收到了表已经存在的错误。 (我没有使用过/除了以前,但认为这是一个很好的学习时间)。
有没有任何好的教程使用SQLite操作或任何建议如何编码这个?我已经看过pysqlite教程和其他我发现但他们没有解决这个问题。
AFAIK一个SQLite数据库是只是一个文件。
要检查数据库是否存在,请检查文件是否存在。
当您打开SQLITE数据库时,如果备份的文件为
如果您尝试打开一个不是数据库的sqlite3数据库的文件,您将获得以下信息:
sqlite3.DatabaseError:文件被加密或不是数据库
所以检查文件是否存在,还要确保尝试如果文件不是sqlite3数据库
,则捕获异常
I have created a Python module that creates and populates several SQLite tables. Now, I want to use it in a program but I don't really know how to call it properly. All the tutorials I've found are essentially "inline", i.e. they walk through using SQLite in a linear fashion rather than how to actually use it in production.
What I'm trying to do is have a method check to see if the database is already created. If so, then I can use it. If not, an exception is raised and the program will create the database. (Or use if/else statements, whichever is better).
I created a test script to see if my logic is correct but it's not working. When I create the try statement, it just creates a new database rather than checking if one already exists. The next time I run the script, I get an error that the table already exists, even if I tried catching the exception. (I haven't used try/except before but figured this is a good time to learn).
Are there any good tutorials for using SQLite operationally or any suggestions on how to code this? I've looked through the pysqlite tutorial and others I found but they don't address this.
AFAIK an SQLITE database is just a file. To check if the database exists, check for file existence.
When you open a SQLITE database it will automatically create one if the file that backs it up is not in place.
If you try and open a file as a sqlite3 database that is NOT a database, you will get this:
"sqlite3.DatabaseError: file is encrypted or is not a database"
so check to see if the file exists and also make sure to try and catch the exception in case the file is not a sqlite3 database
这篇关于在Python程序中使用SQLite的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!