How to connect to a protected Sqlite3 database with Python

H. Dave picture H. Dave · May 17, 2018 · Viewed 11.3k times · Source

I created a SQLite3 database and protected it with a password ("test") thanks to the application DB browser for SQLite. In order to connect to my database via Python, I need to provide the password but I can't figure out how to do that. I tried the following code:

conn=sqlite3.connect("mydatabase.db", Password="test")
cur=conn.cursor()

EDIT:

My SQLite3 database has been encrypted with SQLCipher (see image). enter image description here If I run the following code:

conn=sqlite3.connect("mydatabase.db")
cur=conn.cursor()

I get this error:

sqlite3.DatabaseError: file is encrypted or is not a database

How can I pass the password in order to connect with my db via Python?

EDIT 2

Here a brief summary of what I try to achieve. I am developing an application with Python 3 requiring a pre-populated database but this database needs to be protected with a password. After extensive research, it seems complicated to connect an encrypted SQLite3 database via Python 3. A library calls pysqlcipher exists but only for Python 2.7. My next question will be maybe too broadly and I apology in advance. Is there another portable database that exists allowing me to protect it with a password and still get access to Python? Another idea that I have in mind in order to troubleshoot my problem is to use the zipfile library. This link mentions that the zipfile module does not support encryption but it’s not clear if encryption refers to the SQLite3 database or to the zip file. The idea would be to zip my unprotected DB into a protected zip file as it seems I can do that (link). The goal of this edit is to get new ideas on how to solve my problem. Thanks

Answer

Dan D. picture Dan D. · May 17, 2018

You need the SQLCipher module to read that database. The default SQLite3 module has no support for that. See https://github.com/sqlitebrowser/sqlitebrowser/wiki/Encrypted-Databases