Last active
January 23, 2017 11:30
-
-
Save Makistos/308acfdd4cb6f849e0ad6a01a6a14425 to your computer and use it in GitHub Desktop.
Sqlite3 with Python. #python #sqlite3 #database
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sqlite3 | |
DB_FILE = 'database.db' | |
def db_init(): | |
""" | |
Initialize the sqlite3 database if it doesn't exist or the tables are | |
missing.. | |
:return: n/a | |
""" | |
conn = sqlite3.connect(DB_FILE) | |
c = conn.cursor() | |
c.execute( | |
'CREATE TABLE if not exists results \ | |
(tag text, num integer, status text') | |
conn.commit() | |
conn.close() | |
def db_write(tag, num, status): | |
global DEBUG | |
""" | |
Writes results from a single boot to the database. | |
:param data: Data to write. | |
:param boot: Boot count. | |
:return: n/a | |
""" | |
conn = sqlite3.connect(DB_FILE) | |
c = conn.cursor() | |
row = (tag, num, status) | |
c.execute('INSERT INTO results VALUES (?, ?, ?)', row) | |
conn.commit() | |
conn.close() | |
def db_read(key, filter_value): | |
if not os.path.isfile(DB_FILE): | |
print('No db file detected!') | |
exit() | |
conn = sqlite3.connect(DB_FILE) | |
conn.row_factory = sqlite3.Row | |
c = conn.cursor() | |
cmd = 'SELECT * FROM results' | |
if key != '': | |
cmd = cmd + ' WHERE tag = \"%s\" ' % key | |
try: | |
c.execute(cmd) | |
except sqlite3.OperationalError: | |
print cmd | |
tbl = from_db_cursor(c) | |
print(tbl) | |
conn.close() | |
def db_delete_tag(key): | |
conn = sqlite3.connect(DB_FILE) | |
conn.row_factory = sqlite3.Row | |
c = conn.cursor() | |
if DEBUG: print('Deleting %s from database' % key) | |
c.execute('DELETE FROM results WHERE tag = \'%s\'' % key) | |
conn.commit() | |
conn.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment