3

If I have the following code:

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

.. it will create DB fle called abc.db if it doesn't already exist. What do I do if I don't want to create a new file and only want the connection to succeed if the file already exists?

Eugene Gill
  • 339
  • 4
  • 15

3 Answers3

5

Use sqlite3_open_v2() with either SQLITE_OPEN_READONLY or SQLITE_OPEN_READWRITE.

As described here: http://www.sqlite.org/c3ref/open.html

Vicky
  • 12,934
  • 4
  • 46
  • 54
  • 1
    How do you do that in Python? – Eugene Gill Jun 18 '13 at 13:38
  • 2
    Actually this answer is on the right track. It is possible to call the **sqlite_open_v2()** API from Python, albeit indirectly, by using an URI style database identifier passed to **sqlite3.connect()**. For more gory details see https://stackoverflow.com/a/47351716/4231304. – Jurko Gospodnetić Nov 17 '17 at 13:29
4

You can check if the file already exists or not:

import os
if not os.path.exists('abc.db'):
    conn = sqlite3.connect('abc.db')
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
-2

you can chill, python doesn't create a new database if it is already existing and connects to the pre-existing one!

works in python 2.7 !

try this:

import os
if not os.path.exists('path/to/database'):
    conn = sqlite3.connect('abc.db')
else:
    print "Error! db already exists!"
tenstar
  • 9,816
  • 9
  • 24
  • 45
  • That wasn't the issue. I didn't want to connect to a non-existent database, which causes a new DB to be created, if didn't already exist. – Eugene Gill Jun 18 '13 at 13:46