If I use
$ sqlite3 fileName
sqlite> .s
sqlite>_
and there is no file named fileName, sqlite3 creates a new empty database. Is there a way to avoid this? Ideally, I would like it to retry a couple of times if the file is not found, then fail with an error message. Something like this:
$ sqlite3 --failIfNoSuchFile --retry 3 fileName
sqlite> No such file, retrying ...
sqlite> No such file, retrying ...
sqlite> No such file, retrying ...
sqlite> Aborting...
Error: No file named fileName
$_
Is something like this possible?
The reason I ask is because an 开发者_StackOverflowexisting database we had was crushed and replaced by this new blank database just because a networking problem prevented sqlite3 from finding the file in the first place but did not prevent it from creating the new empty one (and crushing the old one)! At least, that's the most probable theory we've come up with to explain the sudden emptiness of the database (even the structure was gone, .s
returned nothing and the file size was 0)
Any ideas?
btw, in the actual context, a tcl script connects to the database and inserts data. The problem appeared as a "table not found" error and we found out the database file was empty..
I'm not aware of a flag to have sqlite3 do this. Could you just have you tcl script check for the file before calling sqlite3?
Would something like this work:
if {[file exists $dbName] == 1} {
# call sqlite3 in here
return 0
} else {
error "database file not found: $dbName"
}
In the time since the original question & answer were posted, SQLite has added the mode
URI filename parameter. Setting mode=rw
prevents the creation of a database file if it does not already exist:
# new.sqlite does not exist, and is not created
% sqlite3 "file:new.sqlite?mode=rw" "SELECT 1"
Error: unable to open database "file:new.sqlite?mode=rw": unable to open database file
# new.sqlite does not exist, but is automatically created (default behaviour)
% sqlite3 "file:new.sqlite?mode=rwc" "SELECT 1"
1
精彩评论