-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathpythonDatabase.py
More file actions
91 lines (78 loc) · 2.71 KB
/
pythonDatabase.py
File metadata and controls
91 lines (78 loc) · 2.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
import mysql.connector
import re
class DatabaseHandle:
mydb = None
myCursor = None
def __init__(self):
#Initialise the Database with host, username, password
self.mydb = mysql.connector.connect(host="localhost",
user = "root",
passwd = ""
)
self.myCursor = self.mydb.cursor()
def databaseList(self):
#List of Databases
self.myCursor.execute("SHOW DATABASES")
databaselist = list()
for database in self.myCursor:
databaselist.append(database[0])
return databaselist
def connectDatabase(self,databaseName):
#Connect to the database First
databaselist = self.databaseList()
if databaseName in databaselist:
self.mydb = mysql.connector.connect(host="localhost",
user="root",
passwd="",
database = databaseName
)
self.myCursor = self.mydb.cursor()
print("Database "+databaseName+" Connected")
else:
print("Database "+databaseName+" does not exist's")
def createDatabase(self,databaseName):
#Create database
try:
self.myCursor.execute("CREATE DATABASE "+databaseName)
except Exception as e:
print(" "+str(e))
def dropDatabase(self,databaseName):
try:
self.myCursor.execute("DROP DATABASE "+databaseName)
print('Database Deleted '+databaseName)
except Exception as e:
print(" "+str(e))
def currentDatabase(self):
try:
self.myCursor.execute("SELECT database()")
database = [db[0] for db in self.myCursor]
return database[0]
except Exception as e:
print(e)
class TableHandle(DatabaseHandle):
def __init__(self,dObject):
if dObject.currentDatabase() is None:
self.table = None
else:
self.table = dObject.myCursor
def isDatabaseConnected(self):
if self.table is None:
return False
else:
return True
def QueryExecute(self,query):
self.table.execute(query)
return self.table.fetchall()
def tableList(self):
#List of tables
try:
if self.isDatabaseConnected():
self.table.execute("SHOW TABLES")
tablelist = list()
for table in self.table:
tablelist.append(table)
return tablelist
else:
print("No database Selected")
except Exception as e:
print(e)