Accessing an encrypted SQLite3 database in Python (I have the Key) - python

I apologize if its redundant but I couldn't seem to find answer anywhere. I set up a password(encryption key) for my database using DB browser for SQLite3. It uses sqlcipher.
Now I cannot access it. I'm not able to provide password\key. Here's my code:
import sqlite3
from Data.Item import item
import sys
conn = sqlite3.connect('maindb.db')
c = conn.cursor()
c.execute("PRAGMA KEY = 'password'")
def items():
c.execute("SELECT * FROM Item")
data=c.fetchall()
details=items()
My platform is Windows.
I've tried pysqlcipher, It does not gets installed throws an error. How do I proceed from here? What should I do?
My goal is to make my database file unreadable for some obvious reasons.
I get the following error:
c.execute("SELECT * FROM Item")
sqlite3.DatabaseError: file is encrypted or is not a database

Related

conn = sqlite3.connect('<absolut path>') 0

My DB is located here:
D:\sqlite\db
My Python Code is located here:
D:\app\ZAKPRO\R20191121
Code looks this way:
import sqlite3
import os.path
conn = sqlite3.connect('D:\sqlite\db\db_name.db')
c = conn.cursor()
c.execute("INSERT INTO sts_meta (symbol) VALUES( 'tra' ) ")
Error-Message is:
OperationalError: no such table: sts_meta
Can anyone help to correct my code?
I separate DB and Code in different location: Is that fine and advisable?
I only find examples with relative path: Is the access with absolute path not the prefered one in python-sqlite-community? Why is that?
UPDATE
Now I have re-coded, but still facing the same issue:
filename = "dbname.db"
dir = "D:\sqlite\db"
dbpath = pathlib.Path(dir, filename)
sql = ("SELECT * from sts_meta")
conn = sqlite3.connect(dbpath)
c = conn.cursor()
c.execute(sql)
print(c.fetchall())
conn.commit()
This message I receive:
OperationalError: no such table: sts_meta
How to find out wheather I am connected to a database?
Regarding pathlib this is my db-path:
D:\sqlite\db\stocktimeseries.db
It's not that good to use a relative path.
Good practice would be to use path.join from os package in python.
And at any string which contains any characters like backslashes use r'your string'. Adding r before your string will state that the special characters contained in the following string is just a string and they serve no other purpose.
I'm not sure if that is what causes this issue. But if the table exists and you are having issues with path, then path.join can help you out.

comparing a given variable to data in a database and checking to see if it exists

I have a sqlite db of API keys and I want to make something check and see if the given key is in the database.I'm generating the API keys using another python script named apikeygen.py. I'm using python 2.7 and pattern 2.6. This is going to be a data scraping/mining/filtering application that I'm doing just for fun and maybe have a future use for malware analysis.
I need help getting the main piece of code that we will call API.py to check and see if the given API key is in the database.
This is the code for the API.py file so far.
import os, sys; sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", ".."))
import sqlite3 as lite
from pattern.server import App
from pattern.server import MINUTE, HOUR, DAY
app = App("api")
def search_db(key=''):
con = lite.connect('apikeys.db')
with con:
cur = con.cursor()
cur.execute("SELECT * FROM keys")
while True:
row = cur.fetchone()
if row == None:
break
print row[2]
I'm still not really clear what you are asking. Why don't you explicitly query for the key, rather than iterating over your whole table?
cur.execute("SELECT * FROM keys WHERE key = ?", (key,))

Creating a database connection in Python using SQLite

I am new at SQLite in Python and I am trying to create a database connection.
I have the following as a datbase location:
E:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\DATA\master.mdf (i think)
The database is called FTHeader. However, when I try it i get an error saying unable to open database file
any help would be greatly appreciated.
Pick your poison from here and import the module as db and the following should sort you, cribbing from PEP 249:
import adodbapi as db
import adodbapi.ado_consts as db.consts
Cfg={‘server’:’192.168.29.86\\eclexpress’,‘password’:‘xxxx’,‘db’:‘pscitemp’}
constr = r”Provider=SQLOLEDB.1; Initial Catalog=%s; Data Source=%s; user ID=%s; Password=%s; “ \
% (Cfg['db'], Cfg['server'], ‘sa’, Cfg['password'])
conn=db.connect(constr)
You should now be connected to your database after replacing the Cfg dictionary to match your installation.
I have created a database when completing a controlled assesment, here is the code that I have used:
import sqlite3
new_db = sqlite3.connect ('R:\\subjects\\Computing & ICT\\Student Area\\Y11\\Emilyc\\results1.db')
c=new_db.cursor()
c.execute('''CREATE TABLE results1
(
results1_name text,
results1_class number,
quiz_score number)
''')
#Class 1
c.execute('''INSERT INTO results1
VALUES ('John Watson','1','5')''')

using python 2.7 to query sqlite3 database and getting "sqlite3 operational error no such table"

My simple test code is listed below. I created the table already and can query it using the SQLite Manager add-in on Firefox so I know the table and data exist. When I run the query in python (and using the python shell) I get the no such table error
def TroyTest(self, acctno):
conn = sqlite3.connect('TroyData.db')
curs = conn.cursor()
v1 = curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
print v1
conn.close()
When you pass SQLite a non-existing path, it'll happily open a new database for you, instead of telling you that the file did not exist before. When you do that, it'll be empty and you'll instead get a "No such table" error.
You are using a relative path to the database, meaning it'll try to open the database in the current directory, and that is probably not where you think it is..
The remedy is to use an absolute path instead:
conn = sqlite3.connect('/full/path/to/TroyData.db')
You need to loop over the cursor to see results:
curs.execute('''
SELECT acctvalue
FROM balancedata
WHERE acctno = ? ''', acctno)
for row in curs:
print row[0]
or call fetchone():
print curs.fetchone() # prints whole row tuple
The problem is the SQL statment. you must specify the db name and after the table name...
'''SELECT * FROM db_name.table_name WHERE acctno = ? '''

Creating Python Module using pyodbc

want to make small python module that can get data from a database. I have dowload pydbc and it worked fine like this:
import pyodbc
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
Now i want to put this in a module so that i can import it and i dont need to write the code evrytime or locate the file. So i tried to create this like this
import pyodbc
def testDB():
cnxn = pyodbc.connect('DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''')
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
return row
I saved it in: File "C:\Python27\lib\site-packages\testDB.py" and i tried to import it, but i got this error: SyntaxError: 'return' outside function
Im quite new to python, any ideas how i can put this as a module and be able to use import everytime i want to run that code?
As one of the comments says, your indentation is messed up. White space (indentation) is critical in Python. Try it like this:
import pyodbc
def testDB():
cnxn = pyodbc.connect("DRIVER={SQL Server};SERVER=MyDatabase;DATABASE=TestDB;UID='';PWD=''")
cursor = cnxn.cursor()
cursor.execute("select MeasurementValue from TAG_DATA where ItemID=10")
row = cursor.fetchone()
return row
Also, you have to use double quotes for your connection string, since you are using single quotes in the string itself. I've changed them above in to reflect that.
good luck,
Mike

Categories