Advertisement
Guest User

Untitled

a guest
May 6th, 2016
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 8.11 KB | None | 0 0
  1. ####################################
  2. # SQLite/Py Database Manager #
  3. # ? #
  4. ####################################
  5.  
  6.  
  7. import sqlite3, time, datetime, random
  8. from tkinter import *
  9.  
  10.  
  11.  
  12.  
  13. class Window(Frame):
  14. def __init__(self, master = None):
  15. Frame.__init__(self, master)
  16.  
  17. self.master = master
  18.  
  19. self.init_window()
  20.  
  21. def init_window(self):
  22.  
  23. self.master.title("Database Manager v. 0.0.1")
  24.  
  25.  
  26. self.myButton = Button(self.master, text = 'Click to enter text', command=self.print_message)
  27. self.myButton.grid(row=2, column=2)
  28.  
  29. self.usertext = StringVar()
  30. self.myentry = Entry(self.master, textvariable=self.usertext)
  31. #make widget visible
  32. self.myentry.grid(row=1, column=0)
  33.  
  34.  
  35. menu = Menu(self.master)
  36. self.master.config(menu=menu)
  37.  
  38. file = Menu(menu)
  39.  
  40. file.add_command(label='Exit', command=self.client_exit)
  41.  
  42.  
  43. menu.add_cascade(label='File', menu=file)
  44.  
  45. edit = Menu(menu)
  46.  
  47. edit.add_command(label='Undo')
  48. menu.add_cascade(label='Edit', menu=edit)
  49.  
  50. def print_message(self):
  51. print (self.usertext.get())
  52.  
  53. def client_exit(self):
  54. exit()
  55.  
  56. window = Window
  57.  
  58. root = Tk()
  59. root.geometry("400x300")
  60.  
  61. app = Window(root)
  62. root.mainloop()
  63.  
  64.  
  65.  
  66.  
  67. class DatabaseManager(object):
  68. def __init__(self, db):
  69. self.conn = sqlite3.connect(db)
  70. self.conn.execute('pragma foreign_keys = on')
  71. self.conn.commit()
  72. self.c = self.conn.cursor()
  73.  
  74. # Create a query if there are not paramaters to be passed
  75. def query_params(self, arg, params=None):
  76. self.c.execute(arg, params)
  77. self.conn.commit()
  78. return self.c
  79. # Create a query if there are parameters that need tob e passed
  80. def query(self, arg):
  81. self.c.execute(arg)
  82. self.conn.commit()
  83. return self.c
  84.  
  85. #fetch info on description of execution
  86. def fetch(self):
  87. return self.c.fetchall()
  88.  
  89. def __del__(self):
  90. self.conn.close()
  91.  
  92. conn = sqlite3.connect("connect.db")
  93. c = conn.cursor()
  94.  
  95. dbmgr = DatabaseManager("connect.db")
  96.  
  97. #print(pygame.font.get_fonts())
  98.  
  99. while 1 > 0:
  100. print ("\n")
  101. #Creates a table in the sql db based on user input
  102.  
  103. ### ADD PRIMARY KEY ###
  104. def create_table():
  105. name = input("Enter name of the table you want to create: ")
  106. values = []
  107. table = True
  108.  
  109. while table:
  110. val = input("\nEnter values and value type e.g.: TELNUM INT, press return key for each value entered. Once all values entered, type 'done': ")
  111.  
  112. if val != 'done':
  113. values.append(val)
  114. print (values)
  115.  
  116. else:
  117. output = ""
  118. for i in values:
  119. output += i + ","
  120. output = output[:-1]
  121. query = "CREATE TABLE " +name+ "("+output+")"
  122. dbmgr.query(query)
  123. table = False
  124.  
  125.  
  126. #creates as any rows as there are names in john.txt
  127.  
  128. def quantity():
  129. x = random.randint(1000000, 9999999)
  130. file = open("john.txt", "r")
  131.  
  132. for line in file:
  133. query = "INSERT INTO test (playerNAME, playerID) VALUES (?, ?)"
  134. params = (line, x)
  135. dbmgr.query_params(query, params)
  136.  
  137. x = random.randint(1000000, 9999999)
  138.  
  139.  
  140. #deletes specified table from db
  141.  
  142. def drop_table():
  143. i = 0
  144. tables = []
  145. dbmgr.query("SELECT name FROM sqlite_master WHERE type='table';")
  146. rows = c.fetchall()
  147. for row in rows:
  148. method = str(i)+". "+str(row[0])
  149. tables.append(method)
  150. i += 1
  151.  
  152. print (tables)
  153. user_input = int(input("Select table number you would like to delete: "))
  154. drop = (tables[user_input][3:])
  155. #will result in error if there are more than 9 tables and one of the 10+ is selected
  156. dbmgr.query("DROP TABLE " + drop)
  157.  
  158. #Insert or change values in a table in the current database
  159. def modify_values():
  160. available_tables = []
  161.  
  162.  
  163. def insert_values():
  164.  
  165. dbmgr.query("SELECT name FROM sqlite_master WHERE type='table';")
  166. i = 0
  167. rows = dbmgr.fetch()
  168. for row in rows:
  169. method = str(i)+". "+str(row[0])
  170. available_tables.append(method)
  171. i += 1
  172.  
  173.  
  174. print (available_tables)
  175.  
  176. try:
  177. user_input = int(input("Enter number of table to enter values into:\n~ "))
  178.  
  179. except (ValueError, IndexError):
  180. print ("error")
  181.  
  182. edit = available_tables[user_input][3:]
  183. dbmgr.query("SELECT * FROM " +edit)
  184. columns = dbmgr.c.description
  185.  
  186.  
  187. values = [x[0] for x in columns]
  188. values = str(values)
  189. values = values.replace("'", "")
  190. values = values.replace("[", "(")
  191. values = values.replace("]", ")")
  192.  
  193.  
  194. user = input("Enter values you would like to insert into the table you chose, e.g.\n 'EmployeeName', 5032346345, 'EmployeeName@gmail.com':\n~ ")
  195. user2 = input("Enter values you would like to insert into the table you chose, e.g.\n 'EmployeeName', 5032346345, 'EmployeeName@gmail.com':\n~ ")
  196. query = "INSERT INTO " +edit+" "+values+" VALUES (?, ?)"
  197.  
  198. dbmgr.query_params(query, (user, user2))
  199.  
  200.  
  201.  
  202.  
  203. def change_values():
  204. tables = []
  205. available_tables = []
  206.  
  207. dbmgr.query("SELECT name FROM sqlite_master WHERE type='table';")
  208. i = 0
  209. rows = c.fetchall()
  210. for row in rows:
  211. method = str(i)+". "+str(row[0])
  212. available_tables.append(method)
  213. i += 1
  214.  
  215.  
  216.  
  217. print (available_tables)
  218. user_input = int(input("Enter name of table to change values:\n~ "))
  219. dbmgr.query("SELECT * FROM "+available_tables[user_input][3:])
  220. rows = c.fetchall()
  221. for row in rows:
  222. tables.append(row)
  223. print (tables)
  224.  
  225.  
  226.  
  227. print ("1. Change values~\n2. Insert values~")
  228.  
  229. user = input("Select which number to change or insert values into a table:\n~ ")
  230. if user == '2':
  231. insert_values()
  232. elif user == '1':
  233. change_values()
  234.  
  235.  
  236.  
  237.  
  238. #Extract info from db and prints to python console
  239. def read_from_db():
  240.  
  241.  
  242. tables = []
  243. query = "SELECT name FROM sqlite_master WHERE type='table'"
  244. dbmgr.query(query)
  245. print (dbmgr.fetch())
  246.  
  247.  
  248.  
  249.  
  250. ## c.execute('SELECT * FROM stuffToPlot')
  251. ## rows = c.fetchall()
  252. ## for row in rows:
  253. ## print(row)
  254.  
  255. #Attempt to see if the user has connected to the database
  256. ##def connected():
  257. ## try:
  258. ## c.execute('SELECT * FROM stuffToPlot')
  259. ## myfont = pygame.font.SysFont("courier", 15)
  260. ## connText = myfont.render("Connected to Database ["+db+"]", 1, (100,255, 0))
  261. ## screen.blit(connText, (50, 100))
  262. ## except sqlite3.OperationalError or sqlite3.ProgrammingError:
  263. ## myfont = pygame.font.SysFont("courier", 15)
  264. ## connText = myfont.render("Cannot Connect to Database ["+db+"]", 1, (100,255, 0))
  265. ## screen.blit(connText, (50, 100))
  266.  
  267.  
  268.  
  269. #######################################################
  270. #######################################################
  271.  
  272. #asks the user how to alter db
  273.  
  274. user_input = input("Enter either: \n1. View Table in Current Working DB~\n2. Create a table and enter values~\n3. Delete table~\n4. Insert/Change table values\n5. Show Power of SQL\n~ ")
  275. if user_input == '1':
  276. read_from_db()
  277.  
  278. elif user_input == '2':
  279. create_table()
  280.  
  281. elif user_input == '3':
  282. drop_table()
  283.  
  284. elif user_input == '4':
  285. modify_values()
  286.  
  287. elif user_input == '5':
  288. quantity()
  289.  
  290. conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement