Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make sqlite3.connect() fail if the db file does not exist?

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?

like image 768
user1424739 Avatar asked Sep 06 '19 20:09

user1424739


People also ask

What happens if you don't close SQLite connection?

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.

How do I connect to an existing SQLite database?

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.

What does sqlite3 Connect do?

The sqlite3. connect() function returns a Connection object that we will use to interact with the SQLite database held in the file aquarium.

How does Python connect to sqlite3 database?

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.


Video Answer


1 Answers

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
like image 60
PRMoureu Avatar answered Oct 17 '22 03:10

PRMoureu