Begin a "Delete record" procedure

This commit is contained in:
svk28 2017-04-06 15:59:26 +03:00
parent 44baf080db
commit 339e353b2b
2 changed files with 52 additions and 19 deletions

27
dm.py
View File

@ -361,8 +361,6 @@ def selectDataFromDB(tblName, fieldName, fieldValue):
field = rel[0]
fieldRel = rel[1][0]
fieldReplace = rel[1][1]
#field_replace = field_replace.replace(",", ",' ',")
#field_replace = field_replace.replace(",", " || ")
# определяем название таблицы для вложенного запроса
table1 = fieldRel.split('.')[0]
field1 = fieldRel.split('.')[1]
@ -376,10 +374,7 @@ def selectDataFromDB(tblName, fieldName, fieldValue):
fieldReplace = fieldReplace.replace(",", ",' ',")
subqwery = "(SELECT CONCAT(" + fieldReplace + ") FROM " + subqwery + " WHERE " + table1 + "." + field1 + "=" + tblName + "." + field + ") AS " + field
elif db_type == "sqlite":
#print(db_type)
#print(fieldReplace)
fieldReplace = fieldReplace.replace(",", " || ' ' ||")
#print(fieldReplace)
subqwery = "(SELECT (" + fieldReplace + ") FROM " + subqwery +" WHERE "+ table1 + "." + field1 +"="+ tblName +"."+ field +") AS " + field
#print("---" + subqwery)
qwery = qwery.replace(field, subqwery)
@ -391,20 +386,15 @@ def selectDataFromDB(tblName, fieldName, fieldValue):
def selectRelationsDataFromDB(tblSearch, fieldName, fieldValue):
global tbl_struct_list, c, db_type
#print("Ищем связи для:" +tblSearch +','+ fieldName +','+fieldValue)
#print(tbl_struct_list)
searchField = tblSearch + '.' + fieldName
dataList = []
for item in tbl_struct_list:
#print(item)
tblName = item[0]
for field in item[1]:
field = field[0]
for rel in item[2]:
if rel[1][0] == searchField:
#print("таблица:" + tblName + "поле:"+ rel[0] + 'Значение:' + fieldValue)
data = selectDataFromDB(tblName, rel[0], fieldValue)
#print(data)
dataList.append([tblName, data])
return dataList
@ -422,7 +412,24 @@ def getTablesDescriptionOfName(tblName):
if i[0] == tblName:
return(i[1])
# Удаление записи из БД
def deleteRecordsFromDB(tableName, valueList):
global c, db_type
qwery = 'DELETE FROM {} WHERE '.format(tableName)
print(qwery)
subQwery=''
i = 0
for item in getFields(tableName):
print(item[0], item[1])
if item[1] == 'integer':
subQwery = subQwery + item[0] + '=' + valueList[i] + ' AND '
else:
subQwery = subQwery + item[0] + '=\'' + valueList[i] + '\' AND '
#subQwery = '{}'.format(subQwery,item[0])
i += 1
qwery += subQwery
print(qwery)
#initDBstructure()
firstInit()

44
gui.py
View File

@ -10,7 +10,8 @@ from PyQt5.QtWidgets import *
import dm
class MyTable(QTableWidget):
def __init__(self, *args):
def __init__(self, dbTableName = 'NULL', *args):
self.dbTableName = dbTableName
QTableWidget.__init__(self, *args)
self.resizeColumnsToContents()
self.horizontalHeader().setSortIndicatorShown(True)
@ -41,6 +42,7 @@ class MyTable(QTableWidget):
print("Удаляем row:%d, col:%d" % (row, col))
item = self.item(self.currentIndex().row(), self.currentIndex().column())
print("Запись" + item.text())
self.delRecord(row)
elif action == addRecord:
print("Добавить запись ")
addNewRecord()
@ -53,6 +55,17 @@ class MyTable(QTableWidget):
#self.contextMenuEvent(self.cursor())
for currentQTableWidgetItem in self.selectedItems():
print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())
# удаление записи
def delRecord(self, row):
valueList = []
#print(self.dbTableName, row, self.statusTip())
i = 0
print(self.columnCount())
while i < self.columnCount():
valueList.append(self.item(row, i).text())
print(self.item(row, i).text())
i += 1
dm.deleteRecordsFromDB(self.dbTableName, valueList)
# Диалог выбора связанных данных
class RelationDataView(QMainWindow):
@ -79,7 +92,7 @@ class RelationDataView(QMainWindow):
l.addLayout(headBox)
headBox.addWidget(lblHeader)
hboxData = QHBoxLayout()
self.tableViewData = MyTable()
self.tableViewData = MyTable(tblName)
#print(self.widgetsList)
hboxData.addWidget(self.tableViewData)
hboxBtn = QHBoxLayout()
@ -289,7 +302,7 @@ class EditForm(QMainWindow):
relForm.show()
#relForm.setParent(self)
# обработка нажатия на списке таблиц БД
def clickTablesList(tbl_name, tblDataWidget, data='NULL'):
global tblList, tabRelationsData
# удаляем все открытые табы
@ -301,15 +314,21 @@ def clickTablesList(tbl_name, tblDataWidget, data='NULL'):
#print(i)
tabRelationsData.removeTab(i)
i = i+1
i += 1
addDataIntoTable(dm.getTablesNameOfDescription(listTables.model().data(listTables.currentIndex())), tblDataWidget)
# Пишем название активной таблицы БД в строку статуса, эадакая замена глобальной переменной
# как оно и где вылезет будем посмотреть.
tblDataWidget.setStatusTip(dm.getTablesNameOfDescription(listTables.model().data(listTables.currentIndex())))
tblDataWidget.dbTableName = dm.getTablesNameOfDescription(listTables.model().data(listTables.currentIndex()))
# вставка данных в табличный виджет
def addDataIntoTable(tbl_name, tblDataWidget, data='NULL'):
global tblList, tabRelationsData
if data == 'NULL':
data = dm.selectData(tbl_name)
fieldNames = dm.getTableStructure(tbl_name)
#print(fieldNames)
# проверка на наличие записей в таблице
if data:
# количество строк
@ -325,9 +344,11 @@ def addDataIntoTable(tbl_name, tblDataWidget, data='NULL'):
for item in fieldNames:
fName = item[0]
fDescr = item[1]
#### определяем наличие связей и добавляем дополнительные столбцы
####print(fName, fDescr, dm.getRelationsForField(tbl_name, fName))
# установка заголовков столбцов таблицы
tblDataWidget.setHorizontalHeaderItem(n, QTableWidgetItem(fDescr))
n = n + 1
n += 1
n = 0
for key in data:
m = 0
@ -338,6 +359,7 @@ def addDataIntoTable(tbl_name, tblDataWidget, data='NULL'):
n += 1
m += 1
# Показ менб и панели инструментов
def showMenuToolbar(window):
newAction = QAction(QIcon('img/new.gif'), 'Добавить', window)
newAction.setShortcut('Ins')
@ -451,11 +473,12 @@ def showRelationsRecords(fieldIndex, fieldValue):
qweryResult = item[1]
if qweryResult:
#print('report' + str(qweryResult) + 'report')
tblRelationsData = MyTable()
tblRelationsData = MyTable(tbl)
tblRelationsData.setParent(tabRelationsData)
tabRelationsData.addTab(tblRelationsData, dm.getTablesDescriptionOfName(tbl))
addDataIntoTable(tbl, tblRelationsData, qweryResult)
# пишем название активной таблицы БД в строку статуса
tblRelationsData.setStatusTip(tbl)
def main():
global tblList, listTables, tabRelationsData
@ -467,7 +490,7 @@ def main():
listTables = QListWidget()
listTables.setFrameShape(QFrame.StyledPanel)
listTables.setFixedWidth(200)
#tblData = QTableWidget()
# выводим список таблиц в левом поле
tblData = MyTable()
tblData.setFrameShape(QFrame.StyledPanel)
@ -484,10 +507,13 @@ def main():
workArea.setLayout(hbox)
showMenuToolbar(mainWin)
listTables.itemClicked.connect(lambda: clickTablesList(dm.getTablesNameOfDescription(listTables.model().data(listTables.currentIndex())), tblData))
# выводим список таблиц в левом поле
tblList = dm.initDBstructure()
for i in tblList:
listTables.addItem(i[1])
#tblData = QTableWidget()
print(dm.getTablesNameOfDescription(listTables.model().data(listTables.currentIndex())))
mainWin.setGeometry(300, 300, 800, 600)
mainWin.setWindowTitle('Data manipulator')