From 6218f36efdb892096a8952507f6d304ac11c08e7 Mon Sep 17 00:00:00 2001 From: ChillerDragon Date: Fri, 5 Oct 2018 22:46:16 +0200 Subject: [PATCH 1/3] Add sql sample --- sql.py | 46 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100755 sql.py diff --git a/sql.py b/sql.py new file mode 100755 index 0000000..b037a2f --- /dev/null +++ b/sql.py @@ -0,0 +1,46 @@ +#!/usr/bin/env python3 +# SAMPLE SQL FILE +# Will create a file in the current directory 'blockchain.db' + +import sqlite3 as lite + +create_table = """ +CREATE TABLE IF NOT EXISTS Blockchain ( + ID INTEGER PRIMARY KEY AUTOINCREMENT, + PubKey TEXT, + Coins INTEGER +); +""" + +def CreateDataBase(): + con = lite.connect("blockchain.db") + c = con.cursor() + c.execute(create_table) + print("Table Blockchain created.") + +def DeleteDataBase(): + con = lite.connect("blockchain.db") + with con: + c = con.cursor() + c.execute("DROP TABLE IF EXISTS Blockchain;") + print("Table Blockchain deleted.") + +def AddPubKey(key, coins): + con = lite.connect("blockchain.db") + with con: + c = con.cursor() + c.execute("INSERT INTO Blockchain (PubKey, Coins) VALUES (?, ?);", (key, coins)) + +def PrintPubKeys(): + con = lite.connect("blockchain.db") + with con: + c = con.cursor() + c.execute("SELECT * FROM Blockchain;") + row = c.fetchall() + print(str(row)) + +CreateDataBase() +AddPubKey("91298e9812eh81298he9h182e", 420) +PrintPubKeys() + +DeleteDataBase() From c7f48ac68115e8b695f6b9ccb1c8f45b6b014d27 Mon Sep 17 00:00:00 2001 From: ChillerDragon Date: Fri, 5 Oct 2018 23:13:31 +0200 Subject: [PATCH 2/3] Check if the key is in the database --- sql.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/sql.py b/sql.py index b037a2f..a9dd19a 100755 --- a/sql.py +++ b/sql.py @@ -39,8 +39,20 @@ def PrintPubKeys(): row = c.fetchall() print(str(row)) +def GetCoinsByKey(key): + con = lite.connect("blockchain.db") + with con: + c = con.cursor() + c.execute("SELECT * FROM Blockchain WHERE PubKey = '{k}';".format(k=key)) + row = c.fetchall() + if not row: + return None + return row[0][2] # return the amount of coins + CreateDataBase() AddPubKey("91298e9812eh81298he9h182e", 420) PrintPubKeys() +print(GetCoinsByKey("91298e9812eh81298he9h182e")) # => 420 +print(GetCoinsByKey("invalid_key")) # => None DeleteDataBase() From 14cb554ee930f91a7ef52ba7c568eebbb9e5fe49 Mon Sep 17 00:00:00 2001 From: ChillerDragon Date: Fri, 5 Oct 2018 23:14:02 +0200 Subject: [PATCH 3/3] Ignore database files --- .gitignore | 1 + 1 file changed, 1 insertion(+) create mode 100644 .gitignore diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..98e6ef6 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +*.db