42
НАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ ПОЛІТЕХНІЧНИЙ ІНСТИТУТ імені Ігоря Сікорського» ФАКУЛЬТЕТ ПРИКЛАДНОЇ МАТЕМАТИКИ Кафедра системного програмування та спеціалізованих комп’ютерних систем Лабораторна робота №2 з дисципліни «Бази даних і засоби управління» Виконав студент ІII курсу ФПМ групи КВ-73 Шевченко Д.С. Перевірив: Павловський В.І.

scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

НАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ

«КИЇВСЬКИЙ ПОЛІТЕХНІЧНИЙ ІНСТИТУТ імені Ігоря Сікорського»

ФАКУЛЬТЕТ ПРИКЛАДНОЇ МАТЕМАТИКИ

Кафедра системного програмування та спеціалізованих комп’ютерних систем

Лабораторна робота №2з дисципліни

«Бази даних і засоби управління»

Виконав студент ІII курсуФПМ групи КВ-73

Шевченко Д.С.Перевірив: Павловський В.І.

Київ – 2019

Page 2: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Ознайомлення з базовими операціями СУБД PostgreSQL

Завдання роботи полягає у наступному: 1. Виконати нормалізацію бази даних, яка була створена у лабораторній

роботі №1, до третьої нормальної форми (3НФ);2. Реалізувати функціональні вимоги, наведені нижче.

Функціональні вимоги 1. Реалізувати внесення, редагування та вилучення даних у базі засобами

консольного інтерфейсу;2. Передбачити автоматичне пакетне генерування «рандомізованих» даних

у базі; 3. Забезпечити реалізацію пошуку за двома-трьома атрибутами з двох

сутностей одночасно: для числових атрибутів – у рамках діапазону, для рядкових – як перелічення, для логічного типу – значення True/False, для дат – у рамках діапазону дат;

4. Забезпечити реалізацію повнотекстового пошуку за будь-яким текстовим атрибутом бази даних засобами PostgreSQL з виділенням знайденого фрагменту.

Вимоги до інтерфейсу користувача 1. Використовувати консольний інтерфейс користувача.

Варіант 22

Пошук за атрибутами – діапазон дат та логічний тип.Повнотекстовий пошук – слово не входить та обов’язкове входження слова.

Page 3: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Нормалізована модель даних БД «Доставка їжі»

Усі таблиці (відношення) знаходяться в 3 НФ тому, що у кожній із них:1. Всі атрибути є атомарними та відсутні повторення рядків (1НФ);2. Первинний ключ складається лише з одного атрибуту (2НФ);3. Кожний не первинний атрибут не є транзитивно залежним від

первинного ключа (3НФ).

Page 4: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Опис програми

Програма створена для управління базою даних за допомогою базових операцій СУБД PostgreSQL та реалізовує функціональні вимоги, що наведені у завданні. Програма складається з 5 модулів:

1. Main.py – точка входу до програми, містить засоби обробки виключень та повідомлення помилок, викликає функцію головного меню із Сontroller.py;

2. Connect.py – містить функції та засоби для підключення (відключення) БД до (від) програми;

3. Model.py – клас Model, який містить методи для управління даними програми та БД;

4. View.py – клас View, який містить методи для виводу результатів роботи Model на екран;

5. Controller.py – клас Controller, який містить методи для контролю даних введених користувачем та контролю викликів методів Model.

Структура меню програмиМеню програми можна розглядати як її концептуальну модель

Page 5: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Посилання для навігації по тексту програми

1. Main 2. Connect 3. Model

3.1. Завдання 13.1.1. Метод, який додає інформацію до БД 3.1.2. Метод, який видаляє інформацію з БД 3.1.3. Метод, який оновлює інформацію в БД

3.2. Завдання 2 3.2.1. Метод, який створює випадкову інформацію і додає її до

таблиці Client 3.3. Завдання 3

3.3.1. Метод, який реалізує вибір інформації за заданими атрибутам у двох таблицях одночасно

3.4. Завдання 4 3.4.1. Метод, який запускає повнотекстовий пошук у БД

4. View 4.1. Метод, який виводить на екран перелік назв таблиць у БД 4.2. Метод, який виводить на екран перелік атрибутів відповідної таблиці

БД4.3. Метод, який виводить на екран вміст таблиць БД 4.4. Метод, який виводить на екран результати вибірки з таблиць БД

5. Controller

Page 6: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Лістинг модуля Main.py

import psycopg2import Connectfrom Controller import Controller

#Catching errorstry: #Making connection connection = Connect.makeConnect() #Creating cursor to control DB cursor = connection.cursor() #Controller call Controller.mainMenu()

except (Exception , psycopg2.Error) as error : print ("PostgreSQL Error: ",error)finally: #Closing connection and cursir cursor.close() connection.close() print("PostgreSQL connection is closed")

Лістинг модуля Connect.py

import psycopg2

#Function that returns connection to DBdef makeConnect(): return psycopg2.connect( user="postgres", password="qwerty", host="127.0.0.1", port="5432", database="Food delivery 2.0", )#Function that closes connection to DBdef closeConnect(connection): connection.commit() connection.close()

Лістинг модуля Controller.py

from Model import Model

class Controller: #Main Method that calls main manu of the controller @staticmethod def mainMenu(): exit = False print('Welcome to DB Controller program') while not exit: print(''' Main menu 0 => Show one table

Page 7: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

1 => Show all tables 2 => Insert data 3 => Delete data 4 => Update data 5 => Select data 6 => Search text 7 => Randomize data in Client 8 => Exit''')

choise = input('\nMake your choise => ') if choise == '0': Model.showOneTable() elif choise == '1': Model.showAllTables() elif choise == '2': end_insert = False while not end_insert: Model.insert() incorrect = True while incorrect: num = input('\nContinue insertion? 1 - Yes; 2 - No =>') if num == '2': end_insert = True incorrect = False elif num == '1': incorrect = False pass else: print('\nIncorrect input, try again.') elif choise == '3': end_delete = False while not end_delete: Model.delete() incorrect = True while incorrect: num = input('\nContinue deletion? 1 - Yes; 2 - No =>') if num == '2': end_delete = True incorrect = False elif num == '1': incorrect = False pass else: print('\nIncorrect input, try again.') elif choise == '4': end_update = False while not end_update: Model.update() incorrect = True while incorrect: num = input('\nContinue updation? 1 - Yes; 2 - No =>') if num == '2': end_update = True incorrect = False elif num == '1': incorrect = False pass else:

Page 8: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

print('\nIncorrect input, try again.') elif choise == '5': end_select = False while not end_select: Model.select() incorrect = True while incorrect: num = input('\nContinue selection? 1 - Yes; 2 - No =>') if num == '2': end_select = True incorrect = False elif num == '1': incorrect = False pass else: print('\nIncorrect input, try again.') elif choise == '6': end_seacrh = False while not end_seacrh: Model.text_search() incorrect = True while incorrect: num = input('\nContinue to find? 1 - Yes; 2 - No =>') if num == '2': end_seacrh = True incorrect = False elif num == '1': incorrect = False pass else: print('\nIncorrect input, try again.') elif choise == '7': end_random = False while not end_random: Model.random() incorrect = True while incorrect: num = input('\nContinue randomizition? 1 - Yes; 2 - No =>') if num == '2': end_random = True incorrect = False elif num == '1': incorrect = False else: print('\nIncorrect input, try again.') elif choise == '8': exit = True else: print('\nIncorrect input, try again.') incorrect = True while incorrect: end = input('\nContinue work with DB? 1 - Yes; 2 - No. = >') if end == '2': incorrect = False exit = True elif end == '1': incorrect = False

Page 9: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

else: print('\nIncorrect input, try again.')

Лістинг модуля Model.py

import Connectimport randomfrom View import View

#Dictionary with DB table names and them identifierstables = { 1: 'Client', 2: 'Courier', 3: 'Dish', 4: 'Including', 5: 'Order', 6: 'Passport', 7: 'Restaurant', 8: 'Transport',}#Data for randomizition Client tablename = 'name'address = 'address'randomClient = { name: { 1: 'Дмитрий', 2: 'Иван', 3: 'Олег', 4: 'Денис', 5: 'Елена', 6: 'Максим', 7: 'Влад', 8: 'Глеб', 9: 'Ирина', 10: 'Анна', }, address: { 1: 'ул. Крещатик', 2: 'ул. Льва Толстого', 3: 'ул. Киевская', 4: 'ул. Победы', 5: 'ул. Европейская', 6: 'ул. Загадочная', 7: 'ул. Праздничная', 8: 'ул. Шевченка', 9: 'ул. Гоголя', 10: 'ул. Веселая', },}

class Model: # Method that checks valid of the number of table that user input and returns it @staticmethod def validTable(): incorrect = True

Page 10: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

while incorrect: table = input('Choose table number => ') if table.isdigit(): table = int(table) if table >= 1 and table <= 8: incorrect = False else: print('Incorrect input, try again.') else: print('Incorrect input, try again.') return table

#Method that prints all table of DB @staticmethod def showAllTables(): connect = Connect.makeConnect() cursor = connect.cursor() for table in range(1, 9): table_name = '''"''' + tables[table] + '''"''' print(tables[table])

show = 'select * from public.{}'.format(table_name)

print("SQL query => ", show) cursor.execute(show) records = cursor.fetchall() obj = View(table, records) obj.show() cursor.close() Connect.closeConnect(connect)

#Method that prints one table @staticmethod def showOneTable(): View.list() connect = Connect.makeConnect() cursor = connect.cursor()

table = Model.validTable()

table_name = '''"''' + tables[table] + '''"''' print(tables[table])

show = 'select * from public.{}'.format(table_name)

print("SQL query => ", show) print('') cursor.execute(show) records = cursor.fetchall() obj = View(table, records) obj.show() cursor.close() Connect.closeConnect(connect)

#-----------TASK 1----------Inserting data into DB

#Method that inserts data into DB @staticmethod

Page 11: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

def insert(): connect = Connect.makeConnect() cursor = connect.cursor() restart = True while restart: View.list() table = Model.validTable() if table == 1: clid = input("ID = ") clname = "'" + input('Name = ') + "'" claddress = "'" + input('Address = ') + "'" clnumber = input('Number = ')

insert = 'insert into "Client" ("ClID", "ClName", "ClAddress", "ClNumber") values ({}, {}, {}, {})'.format(clid, clname, claddress, clnumber)

restart = False elif table == 2: crid = input('ID = ') crname = "'" + input('Name = ') + "'" crnumber = input('Number = ') crorid = input('OrID = ') crtrid = input('TrID = ') crpsid = input('PsID = ')

insert = 'insert into "Courier" ("CrID", "CrName", "CrNumber", "CrOrID", "CrTrID", "CrPsID") values ({}, {}, {}, {}, {}, {})'.format(crid, crname, crnumber, crorid, crtrid, crpsid)

restart = False elif table == 3: dsid = input('ID = ') dsname = "'" + input('Name = ') + "'" dsprice = input('Price = ')

insert = 'insert into "Dish" ("DsID", "DsName", "DsPrice") values ({}, {}, {})'.format(dsid, dsname, dsprice)

restart = False elif table == 4: incid = input('ID = ') incorderid = input('OrderID = ') incdishid = input('DishID = ')

insert = 'insert into "Including" ("IncID", "IncOrderID", "IncDishID") values ({}, {}, {})'.format(incid, incorderid, incdishid)

restart = False elif table == 5: orid = input('ID = ') ornumber = input('Number = ') orweight = input('Weight = ') ordate = "'" + input('Date = ') + "'" ortype = "'" + input('Type = ') + "'" orclid = input('ClID = ') orrsid = input('RsID = ') ordelivered = "'" + input('Delivered = ') + "'"

Page 12: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

insert = 'insert into "Order" ("OrID", "OrNumber", "OrWeight", "OrDate", "OrType", "OrClID", "OrRsID", "OrDelivered") values ({}, {}, {}, {}, {}, {}, {}, {})'.format(orid, ornumber, orweight, ordate, ortype, orclid, orrsid, ordelivered)

restart = False elif table == 6: psid = input('ID = ') psnumber = "'" + input('Number = ') + "'"

insert = 'insert into "Passport" ("PsID", "PsNumber") values ({}, {})'.format(psid, psnumber)

restart = False elif table == 7: rsid = input('ID = ') rsname = "'" + input('Name = ') + "'" rstype = "'" + input('Type = ') + "'" rsaddress = "'" + input('Address = ') + "'" rsmark = input('Mark = ') rsalltime = "'" + input('AllTime = ') + "'"

insert = 'insert into "Restaurant" ("RsID", "RsName", "RsType", "RsAddress", "RsMark","RsAllTime") values ({}, {}, {}, {}, {}, {})'.format(rsid, rsname, rstype, rsaddress, rsmark, rsalltime)

restart = False elif table == 8: trid = input('ID = ') trname = "'" + input('Name = ') + "'" values = '(' + trid + ',' + trname + ')' insert = '''insert into "Transport" ("TrID", "TrName") values'''+ values insert = 'insert into "Transport" ("TrID", "TrName") values ({}, {})'.format(trid, trname) restart = False else: print('\nIncorrect input, try again.') print(tables[table]) print('SQl query => ',insert) cursor.execute(insert) connect.commit() print('Data added successfully!') cursor.close() Connect.closeConnect(connect)

# ----------TASK 1----------Deleting data from DB

#Method that deletes data from DB @staticmethod def delete(): connect = Connect.makeConnect() cursor = connect.cursor() restart = True while restart: View.list() table = Model.validTable()

Page 13: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

if table == 1: clname = "'" + input('Attribute to delete ClName = ') + "'" delete = 'delete from "Client" where "ClName"= {}'.format(clname) restart = False elif table == 2: crname = "'" + input('Attribute to delete CrName = ') + "'" delete = 'delete from "Courier" where "CrName"= {}'.format(crname) restart = False elif table == 3: dsname = "'" + input('Attribute to delete DsName = ') + "'" delete = 'delete from "Dish" where "DsName"= {}'.format(dsname) restart = False elif table == 4: incorderid = input('Attribute to delete IncOrderID = ') delete = 'delete from "Including" where "IncOrderID"= {}'.format(incorderid) restart = False elif table == 5: orid = input('Attribute to delete OrID = ') delete = 'delete from "Order" where "OrID"= {}'.format(orid) restart = False elif table == 6: psnumber = "'" + input('Attribute to delete PsNumber = ') + "'" delete = 'delete from "Passport" where "PsNumber"= {}'.format(psnumber) restart = False elif table == 7: rsname = "'" + input('Attribute to delete RsName = ') + "'" delete = 'delete from "Restaurant" where "RsName"= {}'.format(rsname) restart = False elif table == 8: trname = "'" + input('Attribute to delete TrName = ') + "'" delete = 'delete from "Transport" where "TrName"= {}'.format(trname) restart = False else: print('\nIncorrect input, try again.') print(tables[table]) print("SQL query => ", delete) cursor.execute(delete) connect.commit() print('Data deleted successfully!') cursor.close() Connect.closeConnect(connect)

#----------TASK 1----------Updating data in DB

#Method that updates data in DB @staticmethod def update(): connect = Connect.makeConnect() cursor = connect.cursor() restart = True while restart: View.list() table = Model.validTable()

Page 14: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

if table == 1: clname = "'" + input('Attribute to update(where) ClName = ') + "'" View.attribute_list(1) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"ClID"= {}'.format(value) in_restart = False elif num == '2': set = '"ClName"= {}'.format(value) in_restart = False elif num == '3': set = '"ClAddress"= {}'.format(value) in_restart = False elif num == '4': set = '"ClNumber"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Client" set {} where "ClName"= {}'.format(set, clname) restart = False pass elif table == 2: crname = "'" + input('Attribute to update(where) ClName = ') + "'" View.attribute_list(2) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"CrID"= {}'.format(value) in_restart = False elif num == '2': set = '"CrName"= {}'.format(value) in_restart = False elif num == '3': set = '"CrNumber"= {}'.format(value) in_restart = False elif num == '4': set = '"CrOrID"= {}'.format(value) in_restart = False elif num == '5': set = '"CrTrID"= {}'.format(value) in_restart = False elif num == '6': set = '"CrPsID"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Courier" set {} where "CrName"= {}'.format(set, crname) restart = False pass elif table == 3: dsname = "'" + input('Attribute to update(where) DsName = ') + "'"

Page 15: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

View.attribute_list(3) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"DsID"= {}'.format(value) in_restart = False elif num == '2': set = '"DsName"= {}'.format(value) in_restart = False elif num == '3': set = '"DsPrice"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Dish" set {} where "DsName"= {}'.format(set, dsname) restart = False pass elif table == 4: incorderid = input('Attribute to update(where) IncOrderID = ') View.attribute_list(4) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"IncID"= {}'.format(value) in_restart = False elif num == '2': set = '"IncOrderID"= {}'.format(value) in_restart = False elif num == '3': set = '"IncDishID"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Including" set {} where "IncOrderID"= {}'.format(set, incorderid) restart = False pass elif table == 5: orid = input('Attribute to update(where) OrID = ') View.attribute_list(5) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"OrID"= {}'.format(value) in_restart = False elif num == '2': set = '"OrNumber"= {}'.format(value) in_restart = False elif num == '3': set = '"OrWeight"= {}'.format(value) in_restart = False

Page 16: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

elif num == '4': set = '"OrDate"= {}'.format(value) in_restart = False elif num == '5': set = '"OrType"= {}'.format(value) in_restart = False elif num == '6': set = '"OrClID"= {}'.format(value) in_restart = False elif num == '7': set = '"OrRsID"= {}'.format(value) in_restart = False elif num == '8': set = '"OrDelivered"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Order" set {} where "OrID"= {}'.format(set, orid) restart = False pass elif table == 6: psnumber = "'" + input('Attribute to update(where) PsNumber = ') + "'" View.attribute_list(6) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"PsID"= {}'.format(value) in_restart = False elif num == '2': set = '"PsName"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Passport" set {} where "PsNumber"= {}'.format(set, psnumber) restart = False pass elif table == 7: rsname = "'" + input('Attribute to update(where) RsName = ') + "'" View.attribute_list(7) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"RsID"= {}'.format(value) in_restart = False elif num == '2': set = '"RsName"= {}'.format(value) in_restart = False elif num == '3': set = '"RsType"= {}'.format(value) in_restart = False elif num == '4':

Page 17: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

set = '"RsAddress"= {}'.format(value) in_restart = False elif num == '5': set = '"RsMark"= {}'.format(value) in_restart = False elif num == '6': set = '"RsAllTime"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Restaurant" set {} where "RsName"= {}'.format(set, rsname) restart = False pass elif table == 8: trname = "'" + input('Attribute to update(where) TrName = ') + "'" View.attribute_list(8) in_restart = True while in_restart: num = input('Number of attribute =>') value = "'" + input('New value of attribute = ') + "'" if num == '1': set = '"TrID"= {}'.format(value) in_restart = False elif num == '2': set = '"TrName"= {}'.format(value) in_restart = False else: print('\nIncorrect input, try again.') update = 'update "Transport" set {} where "TrName"= {}'.format(set, trname) restart = False pass else: print('\nIncorrect input, try again.') print(tables[table]) print("SQL query => ", update) cursor.execute(update) connect.commit() print('Data updeted successfully!') cursor.close() Connect.closeConnect(connect) pass

#----------TASK 3----------

#Method that seletes data from DB @staticmethod def select(): connect = Connect.makeConnect() cursor = connect.cursor() print(''' In my variant you can select data and boolean. This attributes consists in 2 related tables: Order (OrDate, OrDelivered) and Restaurant (RsAllTime). So you can select in them by setting attributes. Date format:(yyyy-mm-dd) Boolean format:(true or false)

Page 18: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

''')

ordateL = "'" + input('OrDate: Between ') + "'" print('and') ordateR = "'" + input() + "'" ordelivered = input('OrDelivered: ') rsalltime = input('RsAllTime: ')

select = 'select "OrID", "OrDate", "OrDelivered","RsName","RsAllTime" from "Order" inner join "Restaurant" on "Order"."OrRsID" = "Restaurant"."RsID" where ("OrDate" between {} and {}) and "OrDelivered" = {} and "RsAllTime" = {} '.format(ordateL, ordateR, ordelivered, rsalltime)

print("SQL query => ", select) cursor.execute(select) records = cursor.fetchall() obj = View(5, records) obj.showSelect()

print('Data selected successfully!') cursor.close() Connect.closeConnect(connect)

#----------TASK 4----------

#Method that runs full text search in DB @staticmethod def text_search(): connect = Connect.makeConnect() cursor = connect.cursor() restart = True while restart: View.list() table = Model.validTable() text = "'" + input('Search text = ') + "'" incorrect = True while incorrect: mode = input(''' 1 -- Word is not included 2 -- Required word entry Choose mode = > ''') if mode.isdigit(): mode = int(mode) if mode >= 1 and mode <= 2: incorrect = False else: print('Incorrect input, try again.') else: print('Incorrect input, try again.')

if mode == 1: if table == 1: text_search = 'select * from "Client" where not (to_tsvector("ClName") || to_tsvector("ClAddress") @@ plainto_tsquery({}))'.format(text) restart = False elif table == 2:

Page 19: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

text_search = 'select * from "Сourier" where not (to_tsvector("CrName") @@ plainto_tsquery({}))'.format(text) restart = False elif table == 3: text_search = 'select * from "Dish" where not (to_tsvector("DsName") @@ plainto_tsquery({}))'.format(text) restart = False elif table == 4: restart = False elif table == 5: text_search = 'select * from "Order" where not (to_tsvector("OrType") @@ plainto_tsquery({}))'.format(text) restart = False elif table == 6: text_search = 'select * from "Passport" where not (to_tsvector("PsNumber") @@ plainto_tsquery({}))'.format(text) restart = False elif table == 7: text_search = 'select * from "Restaurant" where not (to_tsvector("RsName") || to_tsvector("RsType") || to_tsvector("RsAddress") @@ plainto_tsquery({}))'.format(text) restart = False elif table == 8: text_search = 'select * from "Transport" where not (to_tsvector("TrName") @@ plainto_tsquery({}))'.format(text) restart = False else: print('\nIncorrect input, try again.') elif mode == 2: if table == 1: text_search = 'select * from "Client" where to_tsvector("ClName") || to_tsvector("ClAddress") @@ plainto_tsquery({})'.format(text) restart = False elif table == 2: text_search = 'select * from "Сourier" where to_tsvector("CrName") @@ plainto_tsquery({})'.format(text) restart = False elif table == 3: text_search = 'select * from "Dish" where to_tsvector("DsName") @@ plainto_tsquery({})'.format(text) restart = False elif table == 4: pass restart = False elif table == 5: text_search = 'select * from "Order" where to_tsvector("OrType") @@ plainto_tsquery({})'.format(text) restart = False elif table == 6: text_search = 'select * from "Passport" where to_tsvector("PsNumber") @@ plainto_tsquery({})'.format(text) restart = False elif table == 7: text_search = 'select * from "Restaurant" where to_tsvector("RsName") || to_tsvector("RsType") || to_tsvector("RsAddress") @@ plainto_tsquery({})'.format(text) restart = False

Page 20: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

elif table == 8: text_search = 'select * from "Transport" where to_tsvector("TrName") @@ plainto_tsquery({})'.format(text) restart = False else: print('\nIncorrect input, try again.') else: print('\nIncorrect input, try again.')

print(tables[table]) print('SQL query => ',text_search) cursor.execute(text_search) records = cursor.fetchall() obj = View(table, records) obj.show() print('Data searched successfully!') cursor.close() Connect.closeConnect(connect)

#----------TASK2---------- #Method that randoms data into Client table @staticmethod def random(): connect = Connect.makeConnect() cursor = connect.cursor()

incorrect = True while incorrect: num = input('How many clients to random? => ') if num.isdigit(): num = int(num) if num >= 1: incorrect = False else: print('Incorrect input, try again.') else: print('Incorrect input, try again.')

for i in range(1, num + 1): randomName = "'" + randomClient[name][random.randint(1, 10)] + "'" randomAddress = "'" + randomClient[address][random.randint(1, 10)] + ' ' + str(random.randint(1, 100)) + ',' + str(random.randint(1, 100)) + "'" randomNumber = "'" + str(random.randint(1000, 9999)) + str(random.randint(10000, 99999)) + "'"

insert = 'insert into "Client" ("ClID", "ClName", "ClAddress", "ClNumber") values (DEFAULT, {}, {}, {})'.format(randomName, randomAddress, randomNumber)

print("SQL query => ", insert) cursor.execute(insert) connect.commit()

print('Data randomed successfully!') cursor.close() Connect.closeConnect(connect)

Page 21: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Лістинг модуля View.py

class View:

#Initialization of class View def __init__(self, table, records): self.table = table self.records = records

#Method that prints the list of DB tables @staticmethod def list(): print(''' 1 => Client 2 => Courier 3 => Dish 4 => Including 5 => Order 6 => Passport 7 => Restaurant 8 => Transport ''')

#Method that prints the list of attributes of the selected table @staticmethod def attribute_list(table): if table == 1: print(''' 1 => ClID 2 => ClName 3 => ClAddress 4 => ClNumber ''') elif table == 2: print(''' 1 => CrID 2 => CrName 3 => CrNumber 4 => CrOrID 5 => CrTrID 6 => CrPsID ''') elif table == 3: print(''' 1 => DsID 2 => DsName 3 => DsPrice ''') elif table == 4: print(''' 1 => IncID 2 => IncOrderID 3 => IncDishID ''')

Page 22: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

elif table == 5: print(''' 1 => OrID 2 => OrNumber 3 => OrWeight 4 => OrDate 5 => OrType 6 => OrClID 7 => OrRsID 8 => OrDelivered ''') elif table == 6: print(''' 1 => PsID 2 => PsNumber ''') elif table == 7: print(''' 1 => RsID 2 => RsName 3 => RsType 4 => RsAddress 5 => RsMark 6 => RsAllTime ''') elif table == 8: print(''' 1 => TrID 2 => TrName''')

#Method that prints content from a selected table def show(self): print("____________________\n") if self.table == 1: for row in self.records: print("ID = ", row[0]) print("Name = ", row[1]) print("Address = ", row[2]) print("Number = ", row[3]) print("____________________\n") elif self.table == 2: for row in self.records: print("ID = ", row[0]) print("Name = ", row[1]) print("Number = ", row[2]) print("OrID = ", row[3]) print("TrID = ", row[4]) print("PsID = ", row[5]) print("____________________\n") elif self.table == 3: for row in self.records: print("ID = ", row[0]) print("Name = ", row[1]) print("Price = ", row[2]) print("____________________\n") elif self.table == 4: for row in self.records: print("ID = ", row[0])

Page 23: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

print("OrderID = ", row[1]) print("DishID = ", row[2]) print("____________________\n") elif self.table == 5: for row in self.records: print("ID = ", row[0]) print("Number= ", row[1]) print("Weight = ", row[2]) print("Date = ", row[3]) print("Type = ", row[4]) print("ClID = ", row[5]) print("RsID = ", row[6]) print("Delivered = ", row[7]) print("____________________\n") elif self.table == 6: for row in self.records: print("ID = ", row[0]) print("Number= ", row[1]) print("____________________\n") elif self.table == 7: for row in self.records: print("ID = ", row[0]) print("Number= ", row[1]) print("Type = ", row[2]) print("Address = ", row[3]) print("Mark = ", row[4]) print("AllTime = ", row[5]) print("____________________\n") elif self.table == 8: for row in self.records: print("ID = ", row[0]) print("Name= ", row[1]) print("____________________\n")

#Method that prints the result of select query def showSelect(self): for row in self.records: print("OrID = ", row[0]) print("OrDate = ", row[1]) print("OrDelivered = ", row[2]) print("RsName = ", row[3]) print("RsAllTime = ", row[4]) print("____________________\n")

Page 24: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Результати роботи програми

Запуск програми:

Завдання 11. Додавання даних до БД (Model.insert()):

Page 25: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Результат:

2. Редагування даних (Model.update()):

Page 26: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Результат:

Page 27: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

3. Видалення даних (Model.delete()):

Результат (порожня таблиця):

Page 28: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Завдання 2. Пакетне генерування даних в таблиці Client (Model.random()):

Page 29: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Результат:

Завдання 3. Пошук за двома-трьома атрибутами з декількох сутностей одночасно за варіантом (Model.select()):

Page 30: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

.

Завдання 4. Повнотекстовий пошук за варіантом (Model.text_search()):1. Слово не входить:

Page 31: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

2. Обов`язкове входження слова:

Page 32: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Дослідження ON DELETE при вилученні даних з батьківської таблиці Client при тому, що в залежній таблиці Order:

Таблиці до видалення:

Page 33: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ
Page 34: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ
Page 35: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ

Видалення:

Таблиці після видалення:

Page 36: scs.kpi.uascs.kpi.ua/sites/default/files/shevchenko_dmytro_kv-73_lr…  · Web viewНАЦІОНАЛЬНИЙ ТЕХНІЧНИЙ УНІВЕРСИТЕТ УКРАЇНИ «КИЇВСЬКИЙ