I am trying to create a function in Python 2.7.3 to open a SQLite database.
This is my code at the moment:
import sqlite3 as lite
import sys
db = r'someDb.sqlite'
def opendb(db):
try:
conn = lite.connect(db)
except sqlite3.Error:
print "Error open db.\n"
return False
cur = conn.cursor()
return [conn, cur]
I have tried the code above and I have observed that the sqlite3 library opens the database declared if exists, or creates a new database if this one doesn’t exist.
Is there a way to check if the database exists with sqlite3 methods or I have to use file operation like os.path.isfile(path)?
In Python 2, you’ll have to explicitly test for the existence using
os.path.isfile:There is no way to force the
sqlite3.connectfunction to not create the file for you.For those that are using Python 3.4 or newer, you can use the newer URI path feature to set a different mode when opening a database. The
sqlite3.connect()function by default will open databases inrwc, that is Read, Write & Create mode, so connecting to a non-existing database will cause it to be created.Using a URI, you can specify a different mode instead; if you set it to
rw, so Read & Write mode, an exception is raised when trying to connect to a non-existing database. You can set different modes when you set theuri=Trueflag when connecting and pass in afile:URI, and add amode=rwquery parameter to the path:See the SQLite URI Recognized Query Parameters documentation for more details on what parameters are accepted.