· 8 years ago · Mar 24, 2018, 10:40 AM
1#database threading prog
2#Ryan McVicker
3import threading
4import sqlite3
5#import os
6#also add the file to the C:\random directory
7#goal is to use threading to add lists of two separate tuples of data into
8# a database
9
10
11class Database:#class for database holding the method for adding data to the database
12 def __init__(self):
13 self.conn = sqlite3.connect("datathread.db")
14
15 self.c = self.conn.cursor()
16
17 self.c.execute("CREATE TABLE IF NOT EXISTS data(name TEXT, age INT)")
18
19 #exception handling?
20 def addData(self,data):#method for adding data to database
21 try:
22 self.c.execute("INSERT INTO data VALUES(?,?)",data)
23 self.conn.commit()
24 print("data successfully added\n")
25
26 except Exception as e:
27 print("data was not added\n")
28 print(e)
29
30
31 def getData(self): #print all data within the data base
32 self.c.execute("SELECT * FROM data")
33 for new in self.c.fetchall():
34 print(new)
35
36
37
38
39def thread_task(data):#task for the thread to complete
40 database = Database()
41 for _ in data:#will loop through array in order to get the tuples of data
42
43 database.addData(_)#calls the method in the database clas
44
45def second_task(data):#method to call method to delete data in database
46 database = Database()
47 for _ in data:
48 database.deleteData(_)
49
50 database.getData()#print out all data in the database after deleting values
51
52
53#list of tuples in order to pass data into the addData
54
55
56first_set = [("ryan",14),("micahel",12),("david",3),("jeff",20)]
57second_set = [("henry",10),("cat",23),("dog",123),("nathan",50)]
58
59# create the two threads for adding data
60first_thread = threading.Thread(target=thread_task,args=(first_set,))
61second_thread = threading.Thread(target=thread_task,args=(second_set,))
62delete_thread = threading.Thread(target=second_task,args=(second_set,))
63
64#starts the threads
65first_thread.start()
66second_thread.start()
67delete_thread.start()