Delete records procedure fixing

This commit is contained in:
svk28 2017-04-14 16:25:31 +03:00
parent 1fa7c96d1b
commit 59b55c1e0f
2 changed files with 66 additions and 20 deletions

20
dm.py
View File

@ -207,8 +207,10 @@ def selectData(tbl):
if db_type == "mysql": if db_type == "mysql":
field_replace = field_replace.replace(",", ",' ',") field_replace = field_replace.replace(",", ",' ',")
#subqwery = "(SELECT CONCAT(" + field_replace + ") FROM " + subqwery + " WHERE " + table1 + "." + field1 + "=" + tbl + "." + field + ") AS " + field #subqwery = "(SELECT CONCAT(" + field_replace + ") FROM " + subqwery + " WHERE " + table1 + "." + field1 + "=" + tbl + "." + field + ") AS " + field
subqwery = "(SELECT CONCAT({}) FROM {} WHERE {}.{}={}.{}) AS {}"\ # subqwery = "(SELECT CONCAT({}) FROM {} WHERE {}.{}={}.{}) AS {}"\
.format(field_replace,subqwery,table1,field1,tbl,field,field) # .format(field_replace,subqwery,table1,field1,tbl,field,field)
subqwery = "(SELECT CONCAT('>', {}, '<', {}) FROM {} WHERE {}.{}={}.{}) AS {}"\
.format(field,field_replace,subqwery,table1,field1,tbl,field,field)
elif db_type == "sqlite": elif db_type == "sqlite":
field_replace = field_replace.replace(",", " || ' ' ||") field_replace = field_replace.replace(",", " || ' ' ||")
#subqwery = "(SELECT (" + field_replace + ") FROM " + subqwery +" WHERE "+ table1 + "." + field1 +"="+ tbl +"."+ field +") AS " + field #subqwery = "(SELECT (" + field_replace + ") FROM " + subqwery +" WHERE "+ table1 + "." + field1 +"="+ tbl +"."+ field +") AS " + field
@ -217,7 +219,7 @@ def selectData(tbl):
qwery = qwery.replace(field, subqwery) qwery = qwery.replace(field, subqwery)
#qwery = qwery.rstrip(',') + " FROM " + tbl + " LIMIT 10000" #qwery = qwery.rstrip(',') + " FROM " + tbl + " LIMIT 10000"
qwery = '{} FROM {} LIMIT 10000'.format(qwery.rstrip(','), tbl) qwery = '{} FROM {} LIMIT 10000'.format(qwery.rstrip(','), tbl)
#print(qwery) print(qwery)
c.execute(qwery) c.execute(qwery)
return c.fetchall() return c.fetchall()
@ -397,7 +399,7 @@ def selectDataFromDB(tblName, fieldName, fieldValue):
#qwery = qwery.rstrip(',') + " FROM " + tblName + " WHERE " + fieldName + '=' + fieldValue #qwery = qwery.rstrip(',') + " FROM " + tblName + " WHERE " + fieldName + '=' + fieldValue
qwery = '{} FROM {} WHERE {}={}'.format(qwery.rstrip(','), tblName, fieldName, fieldValue) qwery = '{} FROM {} WHERE {}={}'.format(qwery.rstrip(','), tblName, fieldName, fieldValue)
#print(qwery) print(qwery)
c.execute(qwery) c.execute(qwery)
return c.fetchall() return c.fetchall()
@ -431,22 +433,26 @@ def getTablesDescriptionOfName(tblName):
# Удаление записи из БД # Удаление записи из БД
def deleteRecordsFromDB(tableName, valueList): def deleteRecordsFromDB(tableName, valueList):
global c, db_type global c, db_type, conn
qwery = 'DELETE FROM {} WHERE '.format(tableName) qwery = 'DELETE FROM {} WHERE '.format(tableName)
print(qwery) #print(qwery)
subQwery='' subQwery=''
i = 0 i = 0
for item in getFields(tableName): for item in getFields(tableName):
print(item[0], item[1]) print(item[0], item[1])
if item[1] == 'integer': if item[1] == 'integer':
#subQwery = subQwery + item[0] + '=' + valueList[i] + ' AND ' #subQwery = subQwery + item[0] + '=' + valueList[i] + ' AND '
subQwery = '{}{}={} AND'.format(subQwery, item[0], valueList[i]) subQwery = '{}{}={} AND '.format(subQwery, item[0], valueList[i])
else: else:
#subQwery = subQwery + item[0] + '=\'' + valueList[i] + '\' AND ' #subQwery = subQwery + item[0] + '=\'' + valueList[i] + '\' AND '
subQwery = "{}{}='{}' AND ".format(subQwery, item[0], valueList[i]) subQwery = "{}{}='{}' AND ".format(subQwery, item[0], valueList[i])
i += 1 i += 1
qwery += subQwery qwery += subQwery
qwery = qwery.rstrip('AND ').replace("='None'", " IS NULL")
print(qwery) print(qwery)
c.execute(qwery)
conn.commit()
return
#initDBstructure() #initDBstructure()
firstInit() firstInit()

66
gui.py
View File

@ -39,9 +39,9 @@ class MyTable(QTableWidget):
if action == delRecord: if action == delRecord:
row = self.rowAt(event.pos().y()) row = self.rowAt(event.pos().y())
col = self.columnAt(event.pos().x()) col = self.columnAt(event.pos().x())
print("Удаляем row:%d, col:%d" % (row, col)) #print("Удаляем row:%d, col:%d" % (row, col))
item = self.item(self.currentIndex().row(), self.currentIndex().column()) item = self.item(self.currentIndex().row(), self.currentIndex().column())
print("Запись" + item.text()) #print("Запись" + item.text())
self.delRecord(row) self.delRecord(row)
elif action == addRecord: elif action == addRecord:
print("Добавить запись ") print("Добавить запись ")
@ -54,18 +54,21 @@ class MyTable(QTableWidget):
#print(self.cursor().pos().x()) #print(self.cursor().pos().x())
#self.contextMenuEvent(self.cursor()) #self.contextMenuEvent(self.cursor())
for currentQTableWidgetItem in self.selectedItems(): for currentQTableWidgetItem in self.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text()) print(currentQTableWidgetItem, currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
# удаление записи # удаление записи
def delRecord(self, row): def delRecord(self, row):
valueList = [] valueList = []
#print(self.dbTableName, row, self.statusTip()) #print(self.dbTableName, row, self.statusTip())
i = 0 i = 0
print(self.columnCount()) #print(self.columnCount())
while i < self.columnCount(): while i < self.columnCount():
valueList.append(self.item(row, i).text()) if self.item(row, i):
print(self.item(row, i).text()) valueList.append(self.item(row, i).text())
else:
valueList.append('')
#print(self.item(row, i).text())
i += 1 i += 1
dm.deleteRecordsFromDB(self.dbTableName, valueList) deleteRecord(self, row, self.dbTableName, valueList)
# Диалог выбора связанных данных # Диалог выбора связанных данных
class RelationDataView(QMainWindow): class RelationDataView(QMainWindow):
@ -324,7 +327,7 @@ def clickTablesList(dbTableName, tblDataWidget, data='NULL'):
# вставка данных в табличный виджет # вставка данных в табличный виджет
def addDataIntoTable(dbTableName, tblDataWidget, data='NULL'): def addDataIntoTable(dbTableName, tblDataWidget, data='NULL'):
global dbTablesList, tabRelationsData global dbTablesList, tabRelationsData, dbFieldRelationValueList
if data == 'NULL': if data == 'NULL':
data = dm.selectData(dbTableName) data = dm.selectData(dbTableName)
fieldNames = dm.getTableStructure(dbTableName) fieldNames = dm.getTableStructure(dbTableName)
@ -349,16 +352,31 @@ def addDataIntoTable(dbTableName, tblDataWidget, data='NULL'):
# установка заголовков столбцов таблицы # установка заголовков столбцов таблицы
tblDataWidget.setHorizontalHeaderItem(n, QTableWidgetItem(fDescr)) tblDataWidget.setHorizontalHeaderItem(n, QTableWidgetItem(fDescr))
n += 1 n += 1
n = 0 m = 0
dbFieldRelationValueList = []
for key in data: for key in data:
m = 0 n = 0
#print(fieldNames, '\n', key)
for item in key: for item in key:
#print(m, n, item)
listRelationTableAndField = dm.getRelationsForField(dbTableName, fieldNames[n][0])
#print('--->', fieldNames[n][1])
if listRelationTableAndField != 'q':
#print('yahooooo', fieldNames[n][0])
itemString = dm.re.search('>([0-9])+<(.+)', str(item))
if itemString:
#print('--->',itemString.groups())
newitem = QTableWidgetItem(itemString.groups()[1])
dbFieldRelationValueList.append([newitem, m, n, itemString.groups()[0], itemString.groups()[1]])
else:
newitem = QTableWidgetItem(str(item))
# преобразуем все типы в строку # преобразуем все типы в строку
newitem = QTableWidgetItem(str(item))
tblDataWidget.setItem(m, n, newitem) tblDataWidget.setItem(m, n, newitem)
n += 1 n += 1
m += 1 m += 1
#print(dbFieldRelationValueList)
# Показ менб и панели инструментов # Показ менб и панели инструментов
def showMenuToolbar(window): def showMenuToolbar(window):
newAction = QAction(QIcon('img/new.gif'), 'Добавить', window) newAction = QAction(QIcon('img/new.gif'), 'Добавить', window)
@ -480,8 +498,30 @@ def showRelationsRecords(fieldIndex, fieldValue):
# пишем название активной таблицы БД в строку статуса # пишем название активной таблицы БД в строку статуса
tblRelationsData.setStatusTip(tbl) tblRelationsData.setStatusTip(tbl)
def deleteRecord(tableWidget, row, dbTableName, valueList):
global dbFieldRelationValueList
#print(tableWidget, row, dbTableName, valueList)
#print(self.columnCount())
i = 0
#print(valueList)
for val in valueList:
#print(tableWidget.item(row, i))
#print('Значение из таблицы-->',valueList[i])
for item in dbFieldRelationValueList:
if item[0] == tableWidget.item(row, i):
#print(item[0])
#print('еще значение',tableWidget.item(row, i).text(), item[0])
value = item[3]
valueList.pop(i)
valueList.insert(i, item[3])
i += 1
#print(valueList)
dm.deleteRecordsFromDB(dbTableName, valueList)
def main(): def main():
global dbTablesList, listDBTables, tabRelationsData global dbTablesList, listDBTables, tabRelationsData, dbFieldRelationValueList
dbFieldRelationValueList = []
app = QApplication(sys.argv) app = QApplication(sys.argv)
mainWin = QMainWindow() mainWin = QMainWindow()
workArea = QWidget() workArea = QWidget()