sqlite3.connect()
will create the db file if it does not exist. I'd like it to fail. Is there a way to do so?
If you leave it open, it stays open until it goes out of scope and garbage collected. At that point it might be safely closed (and I believe sqlite3 does that). But better to be safe than sorry. Close your connections when you will no longer use them.
Use the connect() method To establish a connection to SQLite, you need to pass the database name you want to connect. If you specify the database file name that already presents on the disk, it will connect to it. But if your specified SQLite database file doesn't exist, SQLite creates a new database for you.
The sqlite3. connect() function returns a Connection object that we will use to interact with the SQLite database held in the file aquarium.
Connect To Database #!/usr/bin/python import sqlite3 conn = sqlite3. connect('test. db') print "Opened database successfully"; Here, you can also supply database name as the special name :memory: to create a database in RAM.
The first way is to check the file path with os.path.isfile
:
import sqlite3
import os
my_path = 'database.db' # or 'absolute_path/to/the/file'
if os.path.isfile(my_path):
sqlite3.connect(my_path)
Otherwise you can use the uri=True
parameter to specify an opening mode
and raise an error in case the file is missing.
Without the mode
, the file will be created if not exists, so you can use for example rw
or ro
to avoid the new file :
to open with read & write mode :
sqlite3.connect('file:database.db?mode=rw', uri=True)
to open in read only mode :
sqlite3.connect('file:database.db?mode=ro', uri=True)
This will raise the following error if the file doesn't exists :
sqlite3.OperationalError: unable to open database file
You can find more about these modes in these chapters of the doc :
https://www.sqlite.org/uri.html
https://www.sqlite.org/c3ref/open.html#urifilenamesinsqlite3open
To be able to open files with special characters (special for an URI), another way is to use the following method :
import pathlib
my_db = pathlib.Path('path/to/data?ba=se.db').as_uri()
sqlite3.connect('{}?mode=rw'.format(my_db), uri=True)
# or sqlite3.connect(f'{my_db}?mode=rw', uri=True) with f-string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With