如果新数据库不存在,不想创建它

2024-04-19 03:38:11 发布

您现在位置:Python中文网/ 问答频道 /正文

如果我有以下代码:

conn = sqlite3.connect('abc.db')

。。如果不存在,它将创建名为abc.db的DB-fle。如果我不想创建一个新文件,只想在文件已经存在的情况下连接成功,我该怎么办?在


Tags: 文件代码dbconnect情况connsqlite3abc
3条回答

你可以冷静一下,python不会创建一个新的数据库,如果它已经存在并连接到预先存在的数据库!在

适用于Python2.7!在

试试这个:

import os
if not os.path.exists('path/to/database'):
    conn = sqlite3.connect('abc.db')
else:
    print "Error! db already exists!"

将sqlite3_open_v2()与SQLITE_open_READONLY或SQLITE_open_READWRITE一起使用。在

如下所述: http://www.sqlite.org/c3ref/open.html

您可以检查文件是否已经存在:

import os
if not os.path.exists('abc.db'):
    conn = sqlite3.connect('abc.db')

相关问题 更多 >