Fixed "delete record" procedure. Added "Edit records" function

This commit is contained in:
svk28 2017-05-12 16:25:32 +03:00
parent 59b55c1e0f
commit b2de966586
2 changed files with 57 additions and 21 deletions

13
dm.py
View File

@ -204,13 +204,15 @@ def selectData(tbl):
else:
subqwery = table1
# составляем подзапрос и подменяем им поле в запросе
print(subqwery)
if db_type == "mysql":
field_replace = field_replace.replace(",", ",' ',")
#subqwery = "(SELECT CONCAT(" + field_replace + ") FROM " + subqwery + " WHERE " + table1 + "." + field1 + "=" + tbl + "." + field + ") AS " + field
# subqwery = "(SELECT CONCAT({}) FROM {} WHERE {}.{}={}.{}) AS {}"\
# .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)
subqwery = "(SELECT CONCAT('>', {}.{}, '<', {}) FROM {} WHERE {}.{}={}.{}) AS {}"\
.format(tbl,field,field_replace,subqwery,table1,field1,tbl,field,field)
elif db_type == "sqlite":
field_replace = field_replace.replace(",", " || ' ' ||")
#subqwery = "(SELECT (" + field_replace + ") FROM " + subqwery +" WHERE "+ table1 + "." + field1 +"="+ tbl +"."+ field +") AS " + field
@ -399,6 +401,7 @@ def selectDataFromDB(tblName, fieldName, fieldValue):
#qwery = qwery.rstrip(',') + " FROM " + tblName + " WHERE " + fieldName + '=' + fieldValue
qwery = '{} FROM {} WHERE {}={}'.format(qwery.rstrip(','), tblName, fieldName, fieldValue)
print(qwery)
c.execute(qwery)
return c.fetchall()
@ -435,11 +438,11 @@ def getTablesDescriptionOfName(tblName):
def deleteRecordsFromDB(tableName, valueList):
global c, db_type, conn
qwery = 'DELETE FROM {} WHERE '.format(tableName)
#print(qwery)
#print(valueList)
subQwery=''
i = 0
for item in getFields(tableName):
print(item[0], item[1])
#print(item[0], item[1])
if item[1] == 'integer':
#subQwery = subQwery + item[0] + '=' + valueList[i] + ' AND '
subQwery = '{}{}={} AND '.format(subQwery, item[0], valueList[i])
@ -449,6 +452,8 @@ def deleteRecordsFromDB(tableName, valueList):
i += 1
qwery += subQwery
qwery = qwery.rstrip('AND ').replace("='None'", " IS NULL")
qwery = qwery.rstrip('AND ').replace("=None", " IS NULL")
qwery = qwery.rstrip('AND ').replace("=NULL", " IS NULL")
print(qwery)
c.execute(qwery)
conn.commit()

65
gui.py
View File

@ -33,6 +33,7 @@ class MyTable(QTableWidget):
def contextMenuEvent(self, event):
Rmenu = QMenu(self)
addRecord = Rmenu.addAction("Добавить запись")
editRecord = Rmenu.addAction("Редактировать запись")
delRecord = Rmenu.addAction("Удалить запись")
showRelations = Rmenu.addAction("Показать связанные документы")
action = Rmenu.exec_(self.mapToGlobal(event.pos()))
@ -46,6 +47,13 @@ class MyTable(QTableWidget):
elif action == addRecord:
print("Добавить запись ")
addNewRecord()
elif action == editRecord:
row = self.rowAt(event.pos().y())
col = self.columnAt(event.pos().x())
#print("Удаляем row:%d, col:%d" % (row, col))
item = self.item(self.currentIndex().row(), self.currentIndex().column())
print("Редактировать запись ")
self.editCurrentRecord(row)
elif action == showRelations:
item = self.item(self.currentIndex().row(), self.currentIndex().column())
showRelationsRecords(self.currentIndex().column(), item.text())
@ -69,6 +77,20 @@ class MyTable(QTableWidget):
#print(self.item(row, i).text())
i += 1
deleteRecord(self, row, self.dbTableName, valueList)
# редактирование записи
def editCurrentRecord(self, row):
valueList = []
#print(self.dbTableName, row, self.statusTip())
i = 0
#print(self.columnCount())
while i < self.columnCount():
if self.item(row, i):
valueList.append(self.item(row, i).text())
else:
valueList.append('')
#print(self.item(row, i).text())
i += 1
editRecord(self, row, self.dbTableName, valueList)
# Диалог выбора связанных данных
class RelationDataView(QMainWindow):
@ -240,6 +262,7 @@ class EditForm(QMainWindow):
edit.setValidator(integerValidator)
else:
edit = QLineEdit()
# создаём список полей и соответсвующих им QEdit
self.widgetsList.append([fName, edit])
@ -356,27 +379,24 @@ def addDataIntoTable(dbTableName, tblDataWidget, data='NULL'):
dbFieldRelationValueList = []
for key in data:
n = 0
#print(fieldNames, '\n', 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))
# кривой алгоритм, надо придумывать что-то другое
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))
dbFieldRelationValueList.append([newitem, m, n, 'None', 'None'])
else:
newitem = QTableWidgetItem(str(item))
# преобразуем все типы в строку
tblDataWidget.setItem(m, n, newitem)
n += 1
m += 1
#print(dbFieldRelationValueList)
# Показ менб и панели инструментов
def showMenuToolbar(window):
newAction = QAction(QIcon('img/new.gif'), 'Добавить', window)
@ -497,27 +517,38 @@ def showRelationsRecords(fieldIndex, fieldValue):
addDataIntoTable(tbl, tblRelationsData, qweryResult)
# пишем название активной таблицы БД в строку статуса
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 editRecord(tableWidget, row, dbTableName, valueList):
global dbFieldRelationValueList
editForm = EditForm(dbTableName, dm.getTablesDescriptionOfName(dbTableName))
editForm.show()
i = 0
for val in valueList:
for item in dbFieldRelationValueList:
if item[0] == tableWidget.item(row, i):
value = item[3]
valueList.pop(i)
valueList.insert(i, item[3])
val = item[3]
editForm.widgetsList[i][1].setText(val)
i += 1
print(valueList)
print(editForm.widgetsList)
#dm.deleteRecordsFromDB(dbTableName, valueList)
def main():
global dbTablesList, listDBTables, tabRelationsData, dbFieldRelationValueList