Re: Verifying a database.

Roger Binns <[email protected]>
Newsgroups gmane.comp.python.db.pysqlite.user
Message-ID <[email protected]>
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1

Colin Barnette wrote:
> Hello, I'm writing a sqlite database accessprogram and I am wondering
> how I might be able to verify that a specified file by the user really
> is a sqlite database.
> 
> I tried:
> 
>        try:
>            dbcon = sqlite.connect(self.dbpath[0])
>            db = dbcon.cursor()
>        except:
>            print "Database Open Error."
> 
> but, it seems that even if the file is a .jpg or .py it still makes
> the connection.

SQLite doesn't actually look at the contents of the file until you issue
a query.  At that point it reads the schema etc if it hasn't done so
already.  The connect will also work for non-existent files.  You could
try this code (my mail client will wrap it).

try:
  sqlite.connection(self.dbpath[0]).cursor().execute("select count(*)
from sqlite_master")
except:
  print "Database error"

Note that this can also fail for other reasons.  For example if there is
a virtual table in the database and it hasn't been registered yet.

Another test is this.

open(self.dbpath[0], "rb").read(16)=="SQLite format 3\0"

You must make sure that the filename is unicode though.  If it is not in
ascii or unicode then Python may convert it one way and SQLite will
convert it another way and you'll end up referring to different files.

Roger
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.6 (GNU/Linux)

iD8DBQFFrbWMmOOfHg372QQRAt7cAJwOlFnaRVXchZ84JDgK1+guGpqXzwCgvtnU
3MdVyN69jb5vr/s3XN4zGIg=
=MQut
-----END PGP SIGNATURE-----
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.