In short, I need help simplifying and optimizing this code because, now that I have switched to a tree widget from 2 list widgets, loading the tables has increased by roughly 3-4 seconds (it used to be almost instant). I would also like to shorten this function if possible.
--- Background Info ---
self.tableData -- The table that the information is being displayed to
getItem() -- a function that when a table of a database is selected, returns the database name (var[0]) and the table name (var[1])
columnNames -- Returns the column names for the table
rows -- returns the total number of rows in the table
g -- index value for the row
h -- index value for the column the data will go in
-- forgot what i, j, k do because I was working on other parts of the program, but they are needed (been some time now)
Note: This code belongs to a class which I have not included
def LoadTable():
self.tableData.clear()
if getItem() != None:
var = getItem()
try:
ccnnxx = mysql.connector.connect(user=self.uname.text(), password=self.upass.text(), host=self.uhost.text(), port=self.uport.text(), database = var[0])
cursor = ccnnxx.cursor()
self.tableData.setRowCount(0)
self.tableData.setColumnCount(0)
header = self.tableData.horizontalHeader()
item = getItem()
cursor.execute("SELECT * FROM " + var[1])
rows = cursor.fetchall()
self.tableData.setRowCount(cursor.rowcount)
ccnnxx.close()
self.tableData.setColumnCount(len(rows[0]))
columnNames = [a[0] for a in cursor.description]
g = 0
h = 0
i = 0
j = 0
k = 0
counter = 0
for items in columnNames:
item = QtWidgets.QTableWidgetItem()
self.tableData.setHorizontalHeaderItem(g, item)
self.tableData.horizontalHeaderItem(g).setText(QtWidgets.QApplication.translate("MainWindow", columnNames[h], None, -1))
header.setSectionResizeMode(g, QtWidgets.QHeaderView.ResizeToContents)
g += 1
h += 1
for row in rows:
counter += 1
if i < counter:
while j != len(rows[0]):
item = QtWidgets.QTableWidgetItem()
self.tableData.setItem(i, k, item)
self.tableData.item(i, k).setText(QtWidgets.QApplication.translate("MainWindow", str(row[j]), None, -1))
k +=1
j +=1
else:
i +=1
k = 0
j = 0
else:
k = 0
j = 0
except IndexError:
#print('This table has no information!')
pass
except TypeError:
#double right-click protection
pass
else:
pass