Реферат: Проектування дволанкової розподіленої інформаційної системи для роботи з базами даних із використанням SQL Interbase

Проектуваннядволанкової розподіленої інформаційної системи для роботи з БД із використаннямSQL Interbase

Мета:

•        створення БД;

•        створення івикористання індексів та переглядів БД;

•        створення івикористання тригерів, генераторів та збережених процедур на боці SQL-сервера;

•        отриманняпрактичних навичок обміну даними між прикладенням і БД.

Завдання:

Засобами SQL Interbaseнеобхідно створити БД, декілька індексованих таблиць БД (головну і підлеглі) ідекілька їх переглядів, а також зв’язати їх між собою.

Засобами С++Builderстворити оригінальне(!) прикладення, яке повинне надавати мож-ливість:

•        переглядузаписів зв’язаних таблиць БД, у тому числі попередніх і наступних записів та ізвикористанням створених переглядів;

•        фільтраціїзаписів БД із виведенням на екран записів, обраних у діалозі за вказанимикритеріями;

•        інкрементальногопошуку даних у БД за вказаними критеріями;

•        додавання івидалення записи таблиці БД, у тому числі із використанням створених на боціSQL-сервера тригерів, генераторів та збережених процедур;

•        корегуванняполів поточного запису таблиці БД, у тому числі із використанням створе-ної набоці SQL-сервера збереженої процедури.

Вказівки до створенняБД:

Для створення БД ізвикористанням SQL Interbase необхідно:

•        завантажити навиконання прикладення InterBase Windows ISQL, яке за звичай зберігає-ться замаршрутом "<диск>:\Program Files\InterBase Corp\ InterBase\Bin\wisql32.exe", наприклад, “E:\Program Files\InterBase Corp\ InterBase\Bin\wisql32.exe";

•        виконатикоманду File | Create Database … і у віконці, яке з’явилося (мал. 1.1), вказатинаведені параметри (параметри можуть бути довільними);

•        виконатикоманду Metadata | Show … і у віконці, яке з’явилося (мал. 1.2), у полі ViewInformation On: обрати з меню альтернативу Database. Якщо БД було успішностворено, то у вікні InterBase Windows ISQL з’явиться відповідне повідомлення(мал. 1.3).

•        виконатикоманду File | Commit Work для збереження результатів роботи на диску;

•        далі (вжезасобами С++ Builder) командою Database | Explore завантажити на виконанняприкладення Database Explore, командою Object | New | INTRBASE створити аліасdbP, обрати його на вкладинці Databases і вказати параметри, які наведено намал. 1.4; потім виконати команду Object | Apply для збереження зроблених змін;

•        у прикладенніInterBase Windows ISQL виконати команду File | Run an ISQL Script … і у вікні,що з’явилося (мал. 1.5), вказати ім’я файлу Createdb.sql, в якому набраноскрипт для створення таблиць БД;


 />/>

Малюнок 1.1 Малюнок 1.2

/>

Малюнок 1.3

/>

Малюнок 1.4

 

/>

Малюнок 1.5

Вміст цього файлунаведено нижче:

/*з’єднаннязБД*/

CONNECT«e:\Lr2\dbP\dbP.gdb» USER «SYSDBA» PASSWORD«masterkey»;

/*створеннятаблиціPERS */

createtable pers(

 Numsmallint Not Null Primary Key,

 Depchar(15),

 Famchar(20) Not Null,

 Nam char(20) Not Null,

 Parchar(20) Not Null,

 Year_bsmallint,

 Sexchar(1),

 Charactblob,

 Photoblob

);

/*створеннятаблиціDEP */

createtable dep(

 Depchar(15) Not Null Primary Key,

 Proisvchar(15)

);

/*заповненнятаблиціPERS */

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(1,«Бухгалтерія»,"Іванов","Іван","Іванович",1950, «ч»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(2,«Цех 1», «Петров», «Петро», «Петрович»,1960, «ч»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(3,«Цех 2», «Сидоров», «Сидор»,«Сидорович», 1955, «ч»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(4,«Цех1», "Іванова","Ірина","Іванівна",1971, «ж»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(5,«Бухгалтерія»,«Миколаєв»,«Микола»,“Миколайович",1930, «ч”);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(6,»Цех2", «Андрієв»,«Андрій»,«Андрійович»,1930, «ч»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(7,«Цех 1», «Борисов», «Борис»,«Борисович», 1937, «ч»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(8,«Цех 1», «Павлов», «Павло», «Павлович»,1975, «ч»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(9,«Бухгалтерія», «Антонова», «Антоніна»,«Антонівна», 1965, «ж»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(10,«Цех 2», «Харитонов», «Харитон»,«Харитонович», 1962, «ч»);

InsertInto PERS(Num, Dep, Fam, Nam, Par, Year_b, Sex)

 Values(11,«Цех 2», "Іванников", "Іван","Іванович", 1975, «ч»);

/* заповнення таблиціDEP */

Insert Into DEP(Dep,Proisv) Values(«Бухгалтерія», «управління»);

InsertInto DEP( Dep,Proisv) Values(«Цех1», «виробництво»);

InsertInto DEP( Dep,Proisv) Values(«Цех2», «виробництво»);

Commit;

Після натискання кнопкиОткрыть треба вказати, що результати виконання скрипту необхідно зберігати у файліResult.txt.Скрипт виконується.

Оглянути схемуствореної таблиці (наприклад, таблиці PERS) можна командою Meta-data| Show … (мал. 1.6)

/>

 Малюнок1.6

SHOWTABLE PERS

NUMSMALLINT Not Null

DEPCHAR(15) Nullable

FAMCHAR(20) Not Null

NAMCHAR(20) Not Null

PARCHAR(20) Not Null

YEAR_BSMALLINT Nullable

SEXCHAR(1) Nullable

CHARACTBLOB segment 80, subtype UNKNOWN Nullable

PHOTOBLOB segment 80, subtype UNKNOWN Nullable

CONSTRAINTINTEG_2:

 Primarykey (NUM)

Оглянутивмістствореноїтаблиці(наприклад,таблиціPERS) можнанаборомзапитуSelect * from PERS у вікніInterBase Windows ISQL, або жзадопомогоюDatabase Explore (мал.1.7):

 />

Малюнок1.7

•        створитиіндекситаблиціPERS, длячоговиконатискрипт,щоміститьсяуфайліCreateINDEXESdbP.sql:

/*З'єднаннязБД*/

CONNECT«e:\Lr3\dbP\dbP.gdb» USER «SYSDBA» PASSWORD«masterkey»;

/*Створенняіндексів*/

createindex Person On PERS Fam,Nam,Par;

createindex DepPerson On PERS Dep,Fam,Nam,Par;

createindex Year On PERS Year_b;

•        створитипереглядитаблиціPERS, длячоговиконатискрипт,щоміститьсяуфайліCreateVIEWSdbP.sql:

/*З'єднаннязБД*/

CONNECT«e:\Lr3\dbP\dbP.gdb» USER «SYSDBA» PASSWORD«masterkey»;

/* Створення переглядівтаблиці PERS за підрозділами */

CreateVIEW dep_1 as

 selectDep, Num, Fam, Nam, Par, Year_b, Sex from Pers

 whereDep = «Бухгалтерія»;

CreateVIEW dep_2 as

 selectDep, Num, Fam, Nam, Par, Year_b, Sex from Pers

 whereDep = «Цех 1»;

CreateVIEW dep_3 as

 selectDep, Num, Fam, Nam, Par, Year_b, Sex from Pers

 whereDep = «Цех 2»;

•        далізасобамиС++Builder командоюDatabase | Explore завантажитинавиконанняприкладенняDatabase Explore і зйогодопомогоюстворитигенераторPERSGEN, як показанонамал.1.8;

/>

Малюнок1.8

•        створититриггерPERSSWITCH таблиці PERS, длячоговиконатискрипт,щомісти-тьсяуфайліCreateTRIGGERdbP.sql:

CONNECT«e:\Lr3\dbP\dbP.gdb» USER «SYSDBA» PASSWORD «masterkey»;

/* Створення триггераPERSSWITCH для збільшення номера запису під час вставки запису у таблицю */

SETTERM ^;

CREATETRIGGER PERSSWITCH FOR PERS

 BEFOREINSERT AS

 BEGIN

 NEW.NUM= GEN_ID(PERSGEN, 1);

 END;^

SETTERM ;^

COMMIT;

•        створити на боціSQL-сервера виконуємі процедури вставки(INSERTdbP), видалення (DELETEdbP)та корегування (UPDATEdbP)таблиці PERS, для чого:

•        виконати скрипт,що міститься у файлі CreateProcINSERTdbP.sql:

CONNECT«e:\Lr3\dbP\dbP.gdb» USER «SYSDBA» PASSWORD«masterkey»;

/*ВиконуємапроцедураINSERTdbP. Додає даніпроспівробітника,вертаєномерзапису*/

SETTERM ^;

CREATEPROCEDURE INSERTdbP

 (

 pDEPCHAR(15),

 pFAMCHAR(20),

 pNAMCHAR(20),

 pPARCHAR(20),

 pYEAR_BINTEGER,

 pSEXCHAR(1)

 )

AS

 BEGIN

 Insertinto PERS (DEP, FAM, NAM, PAR, YEAR_B, SEX)

 VALUES(:pDEP, :pFAM, :pNAM, :pPAR, :pYEAR_B, :pSEX);

 END;^

SETTERM ;^

COMMIT;

•        виконатискрипт,щоміститьсяуфайліCreateProcDELETEdbP.sql:

CONNECT«e:\Lr3\dbP\dbP.gdb» USER «SYSDBA» PASSWORD«masterkey»;

/* Виконуєма процедураDELETEdbP знищення даних про співробітника */

SETTERM ^;

CREATEPROCEDURE DELETEdbP

 (

 pNUMINTEGER

 )

AS

 BEGIN

 DELETEFROM PERS WHERE NUM = :pNUM;

 END;^

SETTERM ;^

COMMIT;

•        виконати скрипт,що міститься у файлі CreateProcUPDATEdbP.sql:

CONNECT«e:\Lr3\dbP\dbP.gdb» USER «SYSDBA» PASSWORD«masterkey»;

/*ВиконуємапроцедураUPDATEdbP.

 Змінюєданіпроспівробітника,вертаєномерзаписучи0, якщоспівробітниканема*/

SETTERM ^;

CREATEPROCEDURE UPDATEdbP

 (

 pDEPCHAR(15),

 pFAMCHAR(20),

 pNAMCHAR(20),

 pPARCHAR(20),

 pYEAR_BINTEGER,

 pSEXCHAR(1)

 )

 RETURNS

 (numberinteger)

AS

 BEGIN

 number= 0;

 SelectNUM From PERS

 Where(FAM = :pFAM) and (NAM = :pNAM) and (PAR = :pPAR)

 Intonumber;

 if(number > 0) then

 UpdatePERS Set DEP = :pDEP, YEAR_B = :pYEAR_B, SEX = :pSEX

 Where(FAM = :pFAM) and (NAM = :pNAM) and (PAR = :pPAR);

 END;^

SET TERM ;^

COMMIT;

У результаті виконанняцих дій буде створено БД зі структурою, що наведено на мал. 1.10.

 />

Малюнок 1.10

Вказівки до створенняпершого прикладення:

Для маніпулюваннятаблицями треба створити проект прикладення (мал. 1.11).

/>

 Малюнок 1.11

Головну форму main_Formнаведено на мал. 1.12 і мал. 1.13.

/>

Малюнок 1.12

/>

Малюнок 1.13

Текстовий опис формиmain_Form:

objectmain_Form: Tmain_Form

 Left= 147

 Top= 103

 Width= 709

 Height= 460

 Caption= 'Лабораторнаробота2'

 Color= clBtnFace

 Font.Charset= DEFAULT_CHARSET

 Font.Color= clWindowText

 Font.Height= -11

 Font.Name= 'System'

 Font.Style= [fsBold]

 OldCreateOrder= True

 Position= poScreenCenter

 OnCreate= FormCreate

 PixelsPerInch= 96

 TextHeight= 16

 objectPageControl: TPageControl

 Left= 421

 Top= 0

 Width= 280

 Height= 428

 ActivePage= find_TabSheet

 Align= alClient

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 MultiLine= True

 ParentFont= False

 TabOrder= 0

 OnChange= PageControlChange

 objectfind_TabSheet: TTabSheet

 Caption= 'Відбір'

 objectselect_GroupBox: TGroupBox

 Left= 1

 Top= 5

 Width= 268

 Height= 212

 Caption= 'Відбірза...'

 TabOrder= 7

 end

 objectsex_RadioGroup: TRadioGroup

 Left= 8

 Top= 120

 Width= 257

 Height= 53

 Caption= ' статтю'

 Columns= 2

 ItemIndex= 0

 Items.Strings= (

 'чоловіча'

 'жіноча')

 TabOrder= 0

 OnClick= minage_CSpinEditChange

 end

 objectspeedfind_GroupBox: TGroupBox

 Left= 0

 Top= 224

 Width= 257

 Height= 169

 Caption= ' Швидкийпошукзапрізвищем'

 TabOrder= 5

 objectImage1: TImage

 Left= 8

 Top= 16

 Width= 105

 Height= 145

 Picture.Data= { }

 Stretch= True

 end

 objectspeedfind_Label: TLabel

 Left= 154

 Top= 42

 Width= 56

 Height= 16

 Caption= 'Прізвище'

 end

 objectspeedfind_Image: TImage

 Left= 32

 Top= 48

 Width= 57

 Height= 73

 Picture.Data= { }

 Stretch= True

 end

 end

 objectage_GroupBox: TGroupBox

 Left= 8

 Top= 32

 Width= 257

 Height= 81

 Caption= ' віком'

 Enabled= False

 TabOrder= 4

 objectminage_Label: TLabel

 Left= 65

 Top= 15

 Width= 28

 Height= 16

 Caption= 'від...'

 end

 objectmaxage_Label: TLabel

 Left= 192

 Top= 15

 Width= 25

 Height= 16

 Caption= 'до...'

 end

 objectminage_Image: TImage

 Left= 8

 Top= 24

 Width= 41

 Height= 49

 Picture.Data= { }

 Stretch= True

 Transparent= True

 end

 objectmaxage_Image: TImage

 Left= 136

 Top= 24

 Width= 41

 Height= 49

 Picture.Data= { }

 Stretch= True

 Transparent= True

 end

 end

 objectspeedfind_Edit: TEdit

 Left= 120

 Top= 296

 Width= 129

 Height= 22

 Hint= 'Вводфамилии'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 ParentShowHint= False

 ShowHint= True

 TabOrder= 1

 OnChange= speedfind_EditChange

 end

 objectminage_CSpinEdit: TCSpinEdit

 Left= 62

 Top= 66

 Width= 65

 Height= 26

 TabStop= True

 MaxValue= 80

 MinValue= 16

 ParentColor= False

 TabOrder= 2

 Value= 16

 OnChange= minage_CSpinEditChange

 end

 objectmaxage_CSpinEdit: TCSpinEdit

 Left= 190

 Top= 66

 Width= 65

 Height= 26

 TabStop= True

 MaxValue= 80

 MinValue= 16

 ParentColor= False

 TabOrder= 3

 Value= 30

 OnChange= minage_CSpinEditChange

 end

 objectselect_BitBtn: TBitBtn

 Left= 8

 Top= 184

 Width= 257

 Height= 25

 Cursor= crHandPoint

 Caption= 'Поновитивідбір'

 TabOrder= 6

 OnClick= select_BitBtnClick

 Kind= bkOK

 end

 end

 objectTabEdit: TTabSheet

 Caption= 'Корегування'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 objectch_GroupBox: TGroupBox

 Left= 2

 Top= 5

 Width= 269

 Height= 388

 Caption= ' Загальнівідомості'

 TabOrder= 9

 objectchdp_Label: TLabel

 Left= 12

 Top= 38

 Width= 50

 Height= 16

 Caption= 'Відділок'

 FocusControl= chdp_ComboBox

 end

 objectchname_Label: TLabel

 Left= 12

 Top= 138

 Width= 25

 Height= 16

 Caption= 'Ім'#39'я'

 FocusControl= chname_Edit

 end

 objectchgrand_Label: TLabel

 Left= 12

 Top= 188

 Width= 73

 Height= 16

 Caption= 'Побатькові'

 FocusControl= chgrand_Edit

 end

 objectchyear_Label: TLabel

 Left= 12

 Top= 232

 Width= 95

 Height= 16

 Caption= 'Рікнародження'

 end

 objectchfam_Label: TLabel

 Left= 12

 Top= 87

 Width= 56

 Height= 16

 Caption= 'Прізвище'

 FocusControl= chfam_Edit

 end

 objectoper_Bevel: TBevel

 Left= 18

 Top= 282

 Width= 251

 Height= 96

 end

 objectoper_Shape: TShape

 Left= 19

 Top= 283

 Width= 248

 Height= 94

 Brush.Color= clBlack

 end

 objectAnimate1: TAnimate

 Left= 24

 Top= 291

 Width= 60

 Height= 80

 Active= True

 FileName= 'Frage.avi'

 StopFrame= 31

 Transparent= False

 end

 end

 objectsex2_RadioGroup: TRadioGroup

 Left= 185

 Top= 218

 Width= 77

 Height= 41

 Caption= 'Стать'

 Columns= 2

 ItemIndex= 0

 Items.Strings= (

 'ч'

 'ж')

 TabOrder= 4

 end

 objectchdp_ComboBox: TComboBox

 Left= 101

 Top= 40

 Width= 162

 Height= 22

 Style= csDropDownList

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ItemHeight= 0

 ParentFont= False

 TabOrder= 0

 end

 objectchfam_Edit: TEdit

 Left= 101

 Top= 90

 Width= 162

 Height= 22

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 1

 Text= 'chfam_Edit'

 end

 objectchname_Edit: TEdit

 Left= 101

 Top= 140

 Width= 162

 Height= 22

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 2

 Text= 'chname_Edit'

 end

 objectchgrand_Edit: TEdit

 Left= 101

 Top= 190

 Width= 162

 Height= 22

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 3

 Text= 'chgrand_Edit'

 end

 objectchadd_Button: TButton

 Left= 88

 Top= 294

 Width= 169

 Height= 25

 Hint= 'Новаязапись'

 Caption= '&Додати'

 ParentShowHint= False

 ShowHint= True

 TabOrder= 5

 OnClick= chadd_ButtonClick

 end

 objectchdelete_Button: TButton

 Left= 88

 Top= 322

 Width= 169

 Height= 25

 Hint= 'Удалениезаписи'

 Caption= '&Видалити'

 ParentShowHint= False

 ShowHint= True

 TabOrder= 6

 OnClick= chdelete_ButtonClick

 end

 objectchpost_Button: TButton

 Left= 88

 Top= 351

 Width= 169

 Height= 25

 Hint= 'Фиксацияизменений'

 Caption= '&Поновити'

 ParentShowHint= False

 ShowHint= True

 TabOrder= 7

 OnClick= chpost_ButtonClick

 end

 objectchyear_CSpinEdit: TCSpinEdit

 Left= 119

 Top= 233

 Width= 50

 Height= 23

 TabStop= True

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 MaxValue= 2000

 MinValue= 1900

 ParentColor= False

 ParentFont= False

 TabOrder= 8

 Value= 1950

 end

 end

 end

 objectleft_Panel: TPanel

 Left= 0

 Top= 0

 Width= 421

 Height= 428

 Align= alLeft

 BevelInner= bvLowered

 Caption= 'left_Panel'

 TabOrder= 1

 objectfind_TPanel: TPanel

 Left= 6

 Top= 5

 Width= 406

 Height= 420

 Caption= 'find_TPanel'

 TabOrder= 1

 objectfind_Label: TLabel

 Left= 110

 Top= 20

 Width= 265

 Height= 24

 Alignment= taCenter

 Caption= 'ПОШУКСПІВРОБІТНИКІВ'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clRed

 Font.Height= -21

 Font.Name= 'Arial Cyr'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 end

 objectdp_GroupBox: TGroupBox

 Left= 8

 Top= 56

 Width= 393

 Height= 57

 Caption= ' Відділок'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 0

 objectdp_ComboBox: TComboBox

 Left= 8

 Top= 24

 Width= 177

 Height= 24

 ItemHeight= 16

 Items.Strings= (

 'Бухгалтерия')

 TabOrder= 0

 OnChange= dp_ComboBoxChange

 end

 end

 objectdp2_GroupBox: TGroupBox

 Left= 200

 Top= 66

 Width= 193

 Height= 41

 Caption= ' підрозділ'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsItalic]

 ParentFont= False

 TabOrder= 1

 objectdp2_DBEdit: TDBEdit

 Left= 5

 Top= 15

 Width= 182

 Height= 23

 Color= clSilver

 DataField= 'PROISV'

 DataSource= dp_DataSource

 Enabled= False

 TabOrder= 0

 end

 end

 objectpr_GroupBox: TGroupBox

 Left= 8

 Top= 115

 Width= 393

 Height= 226

 Caption= ' Співробітники'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 2

 objectBevel1: TBevel

 Left= 10

 Top= 197

 Width= 41

 Height= 24

 end

 objectpr_Label: TLabel

 Left= 16

 Top= 201

 Width= 29

 Height= 16

 Alignment= taCenter

 AutoSize= False

 end

 end

 objectfind_Animate: TAnimate

 Left= 32

 Top= 8

 Width= 48

 Height= 45

 Active= True

 CommonAVI= aviFindComputer

 StopFrame= 8

 end

 objectGroupBox1: TGroupBox

 Left= 8

 Top= 340

 Width= 393

 Height= 77

 Caption= 'ПоточнийоператорSQL'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 4

 objectsql_Label: TLabel

 Left= 11

 Top= 16

 Width= 372

 Height= 57

 AutoSize= False

 Color= clBtnFace

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clRed

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentColor= False

 ParentFont= False

 WordWrap= True

 end

 end

 end

 objectpr_DBGrid: TDBGrid

 Left= 22

 Top= 144

 Width= 379

 Height= 169

 DataSource= pr_DataSource

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsItalic]

 Options= [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs,dgConfirmDelete, dgCancelOnExit]

 ParentFont= False

 TabOrder= 0

 TitleFont.Charset= RUSSIAN_CHARSET

 TitleFont.Color= clWindowText

 TitleFont.Height= -11

 TitleFont.Name= 'Times New Roman'

 TitleFont.Style= [fsItalic]

 OnCellClick= pr_DBGridCellClick

 Columns= <

 item

 Expanded= False

 FieldName= 'FAM'

 Title.Caption= 'Прізвище'

 Width= 59

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'NAM'

 Title.Caption= 'ім'#39'я'

 Width= 57

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'PAR'

 Title.Caption= 'побатькові'

 Width= 67

 Visible= True

 end

 item

 Alignment= taCenter

 Expanded= False

 FieldName= 'YEAR_B'

 Title.Caption= 'рікнародження'

 Width= 85

 Visible= True

 end

 item

 Alignment= taCenter

 Expanded= False

 FieldName= 'SEX'

 Title.Caption= 'стать'

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'AGE'

 Title.Caption= 'вік'

 Width= 38

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'CHARACT'

 Title.Caption= 'характеристика'

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'PHOTO'

 Title.Caption= 'фото'

 Visible= True

 end>

 end

 objectpr_Button: TButton

 Left= 326

 Top= 319

 Width = 75

 Height = 20

 Hint ='Характеристика, фотография'

 Caption= '&Більше...'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 ParentShowHint= False

 ShowHint= True

 TabOrder= 2

 OnClick= pr_ButtonClick

 end

 objectpr_DBNavigator: TDBNavigator

 Left= 73

 Top= 319

 Width= 244

 Height= 20

 DataSource= pr_DataSource

 VisibleButtons= [nbFirst, nbPrior, nbNext, nbLast]

 TabOrder= 3

 end

 end

 objectdp_DataSource: TDataSource

 DataSet= dp_Query

 Left= 140

 Top= 55

 end

 objectpr_DataSource: TDataSource

 DataSet= pr_Query

 Left= 298

 Top= 268

 end

 objectdp_Query: TQuery

 DatabaseName= 'dbP'

 RequestLive= True

 SQL.Strings= (

 'Select* from Dep where DEP = :PDEP')

 Left= 169

 Top= 55

 ParamData= <

 item

 DataType= ftString

 Name= 'PDEP'

 ParamType= ptUnknown

 end>

 objectdp_QueryDEP: TStringField

 FieldName= 'DEP'

 Origin= 'DEP.DEP'

 Size= 15

 end

 objectdp_QueryPROISV: TStringField

 FieldName= 'PROISV'

 Origin= 'DEP.PROISV'

 Size= 15

 end

 end

 objectupdate_Query: TQuery

 DatabaseName= 'dbP'

 DataSource= pr_DataSource

 RequestLive= True

 Left= 356

 Top= 268

 end

 objectpr_Query: TQuery

 BeforePost= pr_QueryBeforePost

 AfterScroll= pr_QueryAfterScroll

 OnCalcFields= pr_QueryCalcFields

 DatabaseName= 'dbP'

 RequestLive= True

 SQL.Strings= (

 'Select* from Pers where DEP = :DEP order by FAM,NAM,PAR')

 Left= 327

 Top= 268

 ParamData= <

 item

 DataType= ftString

 Name= 'DEP'

 ParamType= ptUnknown

 end>

 objectpr_QueryNUM: TSmallintField

 FieldName= 'NUM'

 Origin= 'PERS.NUM'

 end

 objectpr_QueryDEP: TStringField

 FieldName= 'DEP'

 Origin= 'PERS.DEP'

 Size= 15

 end

 objectpr_QueryFAM: TStringField

 FieldName= 'FAM'

 Origin= 'PERS.FAM'

 end

 objectpr_QueryNAM: TStringField

 FieldName= 'NAM'

 Origin= 'PERS.NAM'

 end

 objectpr_QueryPAR: TStringField

 FieldName= 'PAR'

 Origin= 'PERS.PAR'

 end

 objectpr_QueryYEAR_B: TSmallintField

 FieldName= 'YEAR_B'

 Origin= 'PERS.YEAR_B'

 end

 objectpr_QuerySEX: TStringField

 FieldName= 'SEX'

 Origin= 'PERS.SEX'

 Size= 1

 end

 objectpr_QueryCHARACT: TBlobField

 FieldName= 'CHARACT'

 Origin= 'PERS.CHARACT'

 BlobType= ftMemo

 Size= 1

 end

 objectpr_QueryPHOTO: TBlobField

 FieldName= 'PHOTO'

 Origin= 'PERS.PHOTO'

 BlobType= ftGraphic

 Size= 1

 end

 objectpr_QueryAGE: TSmallintField

 Alignment= taCenter

 DisplayLabel= 'Возраст'

 DisplayWidth= 7

 FieldKind= fkCalculated

 FieldName= 'AGE'

 Calculated= True

 end

 end

end

Підлеглуформуcharacter_Form наведено намал.1.14.

/>

 Малюнок1.14

Текстовий опис цієїформи наведено нижче:

objectcharacter_Form: Tcharacter_Form

 Left= 237

 Top= 95

 Width= 318

 Height= 226

 Caption= 'Характеристика'

 Color= clBtnFace

 Font.Charset= DEFAULT_CHARSET

 Font.Color= clWindowText

 Font.Height= -11

 Font.Name= 'MS Sans Serif'

 Font.Style= []

 FormStyle= fsStayOnTop

 OldCreateOrder= True

 Position= poDefaultPosOnly

 PixelsPerInch= 96

 TextHeight= 13

 objectcharacter_DBMemo: TDBMemo

 Left= 0

 Top= 0

 Width= 195

 Height= 194

 Align= alClient

 Alignment= taCenter

 DataField= 'Charact'

 DataSource= main_Form.pr_DataSource

 ScrollBars= ssVertical

 TabOrder= 0

 end

 objectPPhoto: TPanel

 Left= 195

 Top= 0

 Width= 115

 Height= 194

 Align= alRight

 Caption= 'PPhoto'

 TabOrder= 1

 objectphoto_DBImage: TDBImage

 Left= 5

 Top= 42

 Width= 105

 Height= 105

 DataField= 'Photo'

 DataSource= main_Form.pr_DataSource

 TabOrder= 0

 end

 end

end

Для функціонуванняприкладення розроблено програму:

ФайлUdb.h

#ifndefUdbH

#defineUdbH

#include<Classes.hpp>

#include<Controls.hpp>

#include<StdCtrls.hpp>

#include<Forms.hpp>

#include<ComCtrls.hpp>

#include<DBCtrls.hpp>

#include<DBGrids.hpp>

#include<ExtCtrls.hpp>

#include<Grids.hpp>

#include<Mask.hpp>

#include<Db.hpp>

#include<DBTables.hpp>

#include«cspin.h»

#include«CSPIN.h»

#include<jpeg.hpp>

#include<Buttons.hpp>

#include<Graphics.hpp>

classTmain_Form: public TForm

{

__published:        //IDE-managed Components

 TPageControl*PageControl;

 TTabSheet*find_TabSheet;

 TRadioGroup*sex_RadioGroup;

 TEdit*speedfind_Edit;

 TDataSource*dp_DataSource;

 TDataSource*pr_DataSource;

TTabSheet*TabEdit;

 TComboBox*chdp_ComboBox;

 TEdit*chfam_Edit;

 TEdit*chname_Edit;

 TEdit*chgrand_Edit;

 TRadioGroup*sex2_RadioGroup;

 TButton*chadd_Button;

 TButton*chdelete_Button;

 TButton*chpost_Button;

 TCSpinEdit*chyear_CSpinEdit;

 TCSpinEdit*minage_CSpinEdit;

 TCSpinEdit*maxage_CSpinEdit;

 TPanel*left_Panel;

 TPanel*find_TPanel;

 TLabel*find_Label;

 TGroupBox*dp_GroupBox;

 TGroupBox*dp2_GroupBox;

 TGroupBox*pr_GroupBox;

 TDBGrid*pr_DBGrid;

 TButton*pr_Button;

 TDBNavigator*pr_DBNavigator;

 TGroupBox*ch_GroupBox;

 TLabel*chdp_Label;

 TLabel*chname_Label;

 TLabel*chgrand_Label;

 TLabel*chyear_Label;

 TLabel*chfam_Label;

 TGroupBox*age_GroupBox;

 TLabel*minage_Label;

 TLabel*maxage_Label;

 TGroupBox*speedfind_GroupBox;

 TLabel*speedfind_Label;

 TImage*speedfind_Image;

 TImage*minage_Image;

 TImage*maxage_Image;

 TAnimate*find_Animate;

 TBitBtn*select_BitBtn;

 TGroupBox*select_GroupBox;

 TQuery*dp_Query;

 TQuery*update_Query;

 TQuery*pr_Query;

 TComboBox*dp_ComboBox;

 TDBEdit*dp2_DBEdit;

 TStringField*dp_QueryDEP;

 TStringField*dp_QueryPROISV;

 TSmallintField*pr_QueryNUM;

 TStringField*pr_QueryDEP;

 TStringField*pr_QueryFAM;

 TStringField*pr_QueryNAM;

 TStringField*pr_QueryPAR;

 TSmallintField*pr_QueryYEAR_B;

 TStringField*pr_QuerySEX;

 TBlobField*pr_QueryCHARACT;

 TBlobField*pr_QueryPHOTO;

 TSmallintField*pr_QueryAGE;

 TLabel*pr_Label;

 TBevel*Bevel1;

 TGroupBox*GroupBox1;

 TLabel*sql_Label;

 TAnimate*Animate1;

 TBevel*oper_Bevel;

 TShape*oper_Shape;

 TImage*Image1;

         void__fastcall FormCreate(TObject *Sender);

         void__fastcall dp_ComboBoxChange(TObject *Sender);

         void__fastcall pr_ButtonClick(TObject *Sender);

         void__fastcall speedfind_EditChange(TObject *Sender);

         void__fastcall pr_QueryCalcFields(TDataSet *DataSet);

         void__fastcall pr_QueryAfterScroll(TDataSet *DataSet);

         void__fastcall pr_QueryBeforePost(TDataSet *DataSet);

         void__fastcall chadd_ButtonClick(TObject *Sender);

         void__fastcall chdelete_ButtonClick(TObject *Sender);

         void__fastcall chpost_ButtonClick(TObject *Sender);

         void__fastcall PageControlChange(TObject *Sender);

 void__fastcall minage_CSpinEditChange(TObject *Sender);

 void__fastcall select_BitBtnClick(TObject *Sender);

 void__fastcall pr_DBGridCellClick(TColumn *Column);

private:       //User declarations

public:                 //User declarations

         __fastcallTmain_Form(TComponent* Owner);

 unsignedshort Year;

 unsignedshort Month;

 unsignedshort Day;

 boolCanPost;

 intAllPers, CurrentPers;

 AnsiStringsql_Operator;

 void__fastcall Delay(unsigned long int mSeconds);

};

externPACKAGE Tmain_Form *main_Form;

#endif

ФайлUdb.cpp

#include<vcl.h>

#pragmahdrstop

#include«Udb.h»

#include«Udba.h»

#pragmapackage(smart_init)

#pragmalink «cspin»

#pragmalink «CSPIN»

#pragmaresource "*.dfm"

Tmain_Form*main_Form;

__fastcallTmain_Form::Tmain_Form(TComponent* Owner)

        :TForm(Owner)

{}

void__fastcall Tmain_Form::FormCreate(TObject *Sender)

{

 CanPost= false;

 Date().DecodeDate(&Year,&Month,&Day);

 //підрахуваннякількостізаписівутаблиціPERS

 pr_Query->SQL->Clear();

 sql_Operator= «Select * from PERS order by NUM»;

 sql_Label->Caption= sql_Operator;

 pr_Query->SQL->Add(sql_Operator);

 pr_Query->Open();

 pr_Query->First();

 AllPers= 0;

 while(!pr_Query->Eof) {

 ++AllPers;

 pr_Query->Next();

 }

 pr_Query->First();

 dp_Query->SQL->Clear();

 sql_Operator= «Select * from DEP»;

 sql_Label->Caption= sql_Operator;

 dp_Query->SQL->Add(sql_Operator);

 dp_Query->Open();

 dp_Query->First();

 //ЗаповненняComboBox dp_ComboBox таchdp_ComboBox наймуваннями відділків

 dp_ComboBox->Clear();

 chdp_ComboBox->Clear();

 while(!dp_Query->Eof) {

 dp_ComboBox->Items->Add(dp_QueryDEP->AsString);

 chdp_ComboBox->Items->Add(dp_QueryDEP->AsString);

 dp_Query->Next();

 }

 dp_ComboBox->Items->Add(«усівідділки»);

 dp_ComboBox->ItemIndex= dp_ComboBox->Items->Count — 1;

 dp_ComboBoxChange(Sender);

 chdp_ComboBox->ItemIndex= dp_ComboBox->ItemIndex;

 PageControl->ActivePage= find_TabSheet;

}

void__fastcall Tmain_Form::dp_ComboBoxChange(TObject *Sender)

{

 dp_Query->Close();

 dp_Query->SQL->Clear();

 sql_Operator= «Select * from DEP where DEP=:PDEP»;

 sql_Label->Caption= sql_Operator;

 Delay(5000);

 dp_Query->SQL->Add(sql_Operator);

 dp_Query->Params->Items[0]->AsString= dp_ComboBox->Text;

 dp_Query->Open();

 dp_Query->First();

 pr_Query->Close();

 pr_Query->SQL->Clear();

 if(dp_ComboBox->ItemIndex == dp_ComboBox->Items->Count — 1) {

 sql_Operator= «Select * from PERS order by NUM»;

 sql_Label->Caption= sql_Operator;

 Delay(5000);

 pr_Query->SQL->Add(sql_Operator);

 }else {

 sql_Operator= «Select * from PERS where DEP = :DEP order by NUM»;

 sql_Label->Caption= sql_Operator;

 Delay(5000);

 pr_Query->SQL->Add(sql_Operator);

 pr_Query->Params->Items[0]->AsString= dp_ComboBox->Text;

 }

 pr_Query->ExecSQL();

 pr_Query->Open();

 pr_Query->First();

}

void__fastcall Tmain_Form::pr_ButtonClick(TObject *Sender)

{

 if(!character_Form->Visible) character_Form->Show();

}

void__fastcall Tmain_Form::speedfind_EditChange(TObject *Sender)

{

 TLocateOptionsSearchOptions;

 pr_Query->Locate(«FAM»,speedfind_Edit->Text,

 SearchOptions<< loPartialKey << loCaseInsensitive);

}

void__fastcall Tmain_Form::pr_QueryCalcFields(TDataSet *DataSet)

{

 pr_QueryAGE->Value= Year — pr_QueryYEAR_B->Value;

}

void__fastcall Tmain_Form::pr_QueryAfterScroll(TDataSet *DataSet)

{

 //поточнаперсона

 CurrentPers= pr_QueryNUM->AsInteger;

 pr_Label->Caption= IntToStr(CurrentPers);

 if(PageControl->ActivePage == TabEdit) {

 //відображенняданихпропоточнуперсону

 chdp_ComboBox-> ItemIndex =

 chdp_ComboBox->Items->IndexOf(pr_QueryDEP->AsString);

 chfam_Edit->Text= pr_QueryFAM->AsString;

 chname_Edit->Text= pr_QueryNAM->AsString;

 chgrand_Edit->Text= pr_QueryPAR->AsString;

 chyear_CSpinEdit->Value= pr_QueryYEAR_B->AsInteger;

 if(pr_QuerySEX->AsString == «ч»)sex2_RadioGroup->ItemIndex = 0;

 elsesex2_RadioGroup->ItemIndex = 1;

 }

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::pr_QueryBeforePost(TDataSet *DataSet)

{

 if(!CanPost) {

 DataSet->Cancel();

 Abort;

 }

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::chadd_ButtonClick(TObject *Sender)

{// додаваннязаписудотаблиціPERS

 AnsiStringNewSex; // визначення статі

 if(sex2_RadioGroup->ItemIndex == 0) NewSex = «ч»;

 elseNewSex = «ж»;

 update_Query->Close();

 update_Query->SQL->Clear();

 sql_Operator= «Insert into PERS (DEP,FAM,NAM,PAR,YEAR_B,SEX,NUM) values ('»

 +chdp_ComboBox->Text + "','"

 +chfam_Edit->Text + "','"

 +chname_Edit->Text + "','"

 +chgrand_Edit->Text + "','"

 +IntToStr((int)chyear_CSpinEdit->Value) + "','"

 +NewSex + "','"

 +IntToStr(++AllPers) + "')"; // збільшеннякількостізаписівутаблиціPERS

 sql_Label->Caption= sql_Operator;

 Delay(5000);

 update_Query->SQL->Add(sql_Operator);

 update_Query->ExecSQL();// додаваннязапису

 pr_Query->Close();// поновленнявідображенняданихтаблиціPERS

 pr_Query->Open();

 PageControlChange(Sender);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::chdelete_ButtonClick(TObject *Sender)

{ // видаленняпоточного запису з таблиці PERS

 if(Application->MessageBox(«Ви дійсно бажаєте видалити поточнийзапис?»,

 «Підтвердітьвидалення запису»,

 MB_YESNO +MB_ICONEXCLAMATION) == IDYES)

 update_Query->Close();

 update_Query->SQL->Clear();

 sql_Operator= «Delete from PERS where NUM = » + IntToStr(CurrentPers);

 sql_Label->Caption= sql_Operator;

 Delay(5000);

 update_Query->SQL->Add(sql_Operator);

 update_Query->ExecSQL();// видаленнязапису

 pr_Query->Close();// поновленнявідображенняданихталиціPERS

 pr_Query->Open();

 --AllPers;// зменшеннякількостізаписівутаблиціPERS

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::chpost_ButtonClick(TObject *Sender)

{

 AnsiStrings, sSQL;

 constAnsiString s1 = ",";

 s= "";

 sSQL= «Update PERS set »;

 if(pr_QueryDEP->AsString != chdp_ComboBox->Text) {

 s= «відділок»;

 sSQL+= «DEP='» + chdp_ComboBox->Text + "'";

 }

 if(pr_QueryCHARACT->AsString != chfam_Edit->Text) {

 if(s != "") { s += s1; sSQL += s1; }

 s+= " прізвище";

 sSQL+= «FAM='» + chfam_Edit->Text + "'";

 }

 if(pr_QueryCHARACT->AsString != chname_Edit->Text) {

 if(s != "") { s += s1; sSQL += s1; }

 s+= " ім'я";

 sSQL+= «NAM='» + chname_Edit->Text+"'";

 }

 if(pr_QueryCHARACT->AsString != chgrand_Edit->Text) {

 if(s != "") { s += s1; sSQL += s1; }

 s+= " по батькові";

 sSQL+= «PAR='» + chgrand_Edit->Text + "'";

 }

 if(pr_QueryYEAR_B->AsInteger != chyear_CSpinEdit->Value) {

 if(s != "") { s += s1; sSQL += s1; }

 s+= " рік народження";

 sSQL+= «YEAR_B='» + IntToStr((int)(chyear_CSpinEdit->Value));

 }

 if(pr_QuerySEX->AsBoolean != (sex2_RadioGroup->ItemIndex == 0)) {

 if(s != "") { s += s1; sSQL += s1; }

 s+= " стать";

 sSQL+= «SEX='»;

 if(sex2_RadioGroup->ItemIndex== 0) sSQL += «ч'»;

 elsesSQL += «ж'»;

 }

 if(s != "")

 if(Application->MessageBox(

 («Дійснобажаєтезмінити» + s + "?").c_str(),

 «Підтвердітьзанесення змін у базу даних»,

 MB_YESNO+ MB_ICONQUESTION) == IDYES)

 {update_Query->Close();

 update_Query->SQL->Clear();

 sql_Operator= sSQL + " where NUM=" + IntToStr(pr_QueryNUM->AsInteger);

 sql_Label->Caption= sql_Operator;

 Delay(5000);

 update_Query->SQL->Add(sql_Operator);

 update_Query->ExecSQL();

 pr_Query->Close();

 pr_Query->Open();

 CanPost= false;

 };

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::PageControlChange(TObject *Sender)

{

 character_Form->character_DBMemo->ReadOnly=

 !(PageControl->ActivePage== TabEdit);

 if(PageControl->ActivePage == TabEdit) pr_QueryAfterScroll(pr_Query);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::minage_CSpinEditChange(TObject *Sender)

{

 AnsiStrings =

 "(YEAR_B<="+ IntToStr(int(Year — minage_CSpinEdit->Value)) +

 ")and(YEAR_B>="+ IntToStr(int(Year — maxage_CSpinEdit->Value)) +

 ")and(SEX=";

 if(!sex_RadioGroup->ItemIndex) s += "'ч')";

 elses += "'ж')";

 // автоматичнепоновлення відбору записів

 select_BitBtn->Kind= bkCancel;

 select_BitBtn->Caption= «Відмінитивідбір»;

 pr_Query->Filter= s;

 pr_Query->Filtered= true;

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::select_BitBtnClick(TObject *Sender)

{

 if(pr_Query->Filtered) { // відмінарежимуфільтрації

 pr_Query->Filtered= false;

 select_BitBtn->Kind= bkYes;

 select_BitBtn->Caption= «Поновитивідбір»;

 }else { // встановлення режимуфільтрації

 select_BitBtn->Kind= bkCancel;

 select_BitBtn->Caption= «Відмінитивідбір»;

 minage_CSpinEditChange(Sender);

 }

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::pr_DBGridCellClick(TColumn *Column)

{

 if(PageControl->ActivePage == TabEdit) {

 chdp_ComboBox-> ItemIndex =

 chdp_ComboBox->Items->IndexOf(pr_QueryDEP->AsString);

 chfam_Edit->Text= pr_QueryFAM->AsString;

 chname_Edit->Text= pr_QueryNAM->AsString;

 chgrand_Edit->Text= pr_QueryPAR->AsString;

 chyear_CSpinEdit->Value= pr_QueryYEAR_B->AsInteger;

 if(pr_QuerySEX->AsString == «ч»)sex2_RadioGroup->ItemIndex = 0;

 elsesex2_RadioGroup->ItemIndex = 1;

 }

 //поточнаперсона

 CurrentPers= pr_QueryNUM->AsInteger;

 pr_Label->Caption= IntToStr(CurrentPers);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::Delay(unsigned long int mSeconds)

{// затримканадекількамілісекунд

 unsignedlong int FirstTick;

 FirstTick= GetTickCount();

 do

 Application->ProcessMessages();

 while(GetTickCount() — FirstTick <= mSeconds);

}

ФайлUdba.h

//---------------------------------------------------------------------------

#ifndefUdbaH

#defineUdbaH

//---------------------------------------------------------------------------

#include<Classes.hpp>

#include<Controls.hpp>

#include<StdCtrls.hpp>

#include<Forms.hpp>

#include<DBCtrls.hpp>

#include<ExtCtrls.hpp>

//---------------------------------------------------------------------------

classTcharacter_Form: public TForm

{

__published:        //IDE-managed Components

 TDBMemo*character_DBMemo;

         TPanel*PPhoto;

 TDBImage*photo_DBImage;

private:       //User declarations

public:                 //User declarations

         __fastcallTcharacter_Form(TComponent* Owner);

};

//---------------------------------------------------------------------------

externPACKAGE Tcharacter_Form *character_Form;

//---------------------------------------------------------------------------

#endif

ФайлUdba.cpp

//---------------------------------------------------------------------------

#include<vcl.h>

#pragmahdrstop

#include«Udba.h»

#include«Udb.h»

//---------------------------------------------------------------------------

#pragmapackage(smart_init)

#pragmaresource "*.dfm"

Tcharacter_Form*character_Form;

//---------------------------------------------------------------------------

__fastcallTcharacter_Form::Tcharacter_Form(TComponent* Owner)

        :TForm(Owner)

{

}

//---------------------------------------------------------------------------

Длявиконанняприкладеннятребапопередньозавантажитинавиконанняприкладення-серверIBServer.EXE, яке зазвичайзнаходитьсязамаршрутом«E:\Program Files\InterBase Corp\InterBase\Bin\» іобслуговуєзапитидобазиданихInterbase. Після завантаження поточ-ного проекту на виконанняцей сервер виводить на екран запит (мал… 1.15), у полі Password: якого требаввести пароль доступу masterkey..

 

/>

Малюнок 1.15

Форми під часфункціонування прикладення наведено на мал. 1.16 — 1.18.

 />

Малюнок 1.16

/>

Малюнок 1.17

/>

 Малюнок 1.18

Вказівки до створеннядругого прикладення: Для маніпулювання таблицями можна використати корегованийпроект попереднього прикладення (мал. 1.19).

/>

Малюнок 1.19

Головну форму main_Formнаведено на мал. 1.20.

/>

Малюнок 1.20

Текстовийописформиmain_Form:

objectmain_Form: Tmain_Form

 Left= 63

 Top= 22

 Width= 709

 Height= 461

 Caption= 'Лабораторнаробота3'

 Color= clBtnFace

 Font.Charset= DEFAULT_CHARSET

 Font.Color= clWindowText

 Font.Height= -11

 Font.Name= 'System'

 Font.Style= [fsBold]

 OldCreateOrder= True

 Position= poScreenCenter

 OnCreate= FormCreate

 PixelsPerInch= 96

 TextHeight= 16

 objectPageControl: TPageControl

 Left= 421

 Top= 0

 Width= 280

 Height= 429

 ActivePage= find_TabSheet

 Align= alClient

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 MultiLine= True

 ParentFont= False

 TabOrder= 0

 OnChange= PageControlChange

 objectfind_TabSheet: TTabSheet

 Caption= 'Відбір'

 objectselect_GroupBox: TGroupBox

 Left= 1

 Top= 5

 Width= 268

 Height= 212

 Caption= 'Відбірза...'

 TabOrder= 7

 end

 objectsex_RadioGroup: TRadioGroup

 Left= 8

 Top= 120

 Width= 257

 Height= 53

 Caption= ' статтю'

 Columns= 2

 ItemIndex= 0

 Items.Strings= (

 'чоловіча'

 'жіноча')

 TabOrder= 0

 OnClick= minage_CSpinEditChange

 end

 objectspeedfind_GroupBox: TGroupBox

 Left= 0

 Top= 224

 Width= 257

 Height= 169

 Caption= ' Швидкийпошукзапрізвищем'

 TabOrder= 5

 objectImage1: TImage

 Left= 8

 Top= 16

 Width= 105

 Height= 145

 Picture.Data= {}

 Stretch= True

 end

 objectspeedfind_Label: TLabel

 Left= 154

 Top= 50

 Width= 56

 Height= 16

 Caption= 'Прізвище'

 end

 objectspeedfind_Image: TImage

 Left= 32

 Top= 48

 Width= 57

 Height= 73

 Picture.Data= {}

 Stretch= True

 end

 end

 objectage_GroupBox: TGroupBox

 Left= 8

 Top= 32

 Width= 257

 Height= 81

 Caption= ' віком'

 Enabled= False

 TabOrder= 4

 objectminage_Label: TLabel

 Left= 65

 Top= 15

 Width= 28

 Height= 16

 Caption= 'від...'

 end

 objectmaxage_Label: TLabel

 Left= 192

 Top= 15

 Width= 25

 Height= 16

 Caption= 'до...'

 end

 objectminage_Image: TImage

 Left= 8

 Top= 24

 Width= 41

 Height= 49

 Picture.Data= {}

 Stretch= True

 Transparent= True

 end

 objectmaxage_Image: TImage

 Left= 136

 Top= 24

 Width= 41

 Height= 49

 Picture.Data= {}

 Stretch= True

 Transparent= True

 end

 end

 objectspeedfind_Edit: TEdit

 Left= 120

 Top= 310

 Width= 129

 Height= 22

 Hint= 'Вводфамилии'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 ParentShowHint= False

 ShowHint= True

 TabOrder= 1

 OnChange= speedfind_EditChange

 end

 objectminage_CSpinEdit: TCSpinEdit

 Left= 62

 Top= 66

 Width= 65

 Height= 26

 TabStop= True

 MaxValue= 80

 MinValue= 16

 ParentColor= False

 TabOrder= 2

 Value= 16

 OnChange= minage_CSpinEditChange

 end

 objectmaxage_CSpinEdit: TCSpinEdit

 Left= 190

 Top= 66

 Width= 65

 Height= 26

 TabStop= True

 MaxValue= 80

 MinValue= 16

 ParentColor= False

 TabOrder= 3

 Value= 30

 OnChange= minage_CSpinEditChange

 end

 objectselect_BitBtn: TBitBtn

 Left= 8

 Top= 184

 Width= 257

 Height= 25

 Cursor= crHandPoint

 Caption= 'Поновитивідбір'

 TabOrder= 6

 OnClick= select_BitBtnClick

 Kind= bkOK

 end

 end

 objectTabEdit: TTabSheet

 Caption= 'Корегування'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 objectch_GroupBox: TGroupBox

 Left= 2

 Top= 5

 Width= 269

 Height= 388

 Caption= ' Загальнівідомості'

 TabOrder= 9

 objectchdp_Label: TLabel

 Left= 12

 Top= 38

 Width= 50

 Height= 16

 Caption= 'Відділок'

 FocusControl= chdp_ComboBox

 end

 objectchname_Label: TLabel

 Left= 12

 Top= 138

 Width= 25

 Height= 16

 Caption= 'Ім'#39'я'

 FocusControl= chname_Edit

 end

 objectchgrand_Label: TLabel

 Left= 12

 Top= 188

 Width= 73

 Height= 16

 Caption= 'Побатькові'

 FocusControl= chgrand_Edit

 end

 objectchyear_Label: TLabel

 Left= 12

 Top= 232

 Width= 95

 Height= 16

 Caption= 'Рікнародження'

 end

 objectchfam_Label: TLabel

 Left= 12

 Top= 87

 Width= 56

 Height= 16

 Caption= 'Прізвище'

 FocusControl= chfam_Edit

 end

 objectoper_Bevel: TBevel

 Left= 18

 Top= 282

 Width= 251

 Height= 96

 end

 objectoper_Shape: TShape

 Left= 19

 Top= 283

 Width= 248

 Height= 94

 Brush.Color= clBlack

 end

 objectAnimate1: TAnimate

 Left= 24

 Top= 291

 Width= 60

 Height= 80

 Active= True

 FileName= 'Frage.avi'

 StopFrame= 31

 Transparent= False

 end

 end

 objectsex2_RadioGroup: TRadioGroup

 Left= 185

 Top= 218

 Width= 77

 Height= 41

 Caption= 'Стать'

 Columns= 2

 ItemIndex= 0

 Items.Strings= (

 'ч'

 'ж')

 TabOrder= 4

 end

 objectchdp_ComboBox: TComboBox

 Left= 101

 Top= 40

 Width= 162

 Height= 22

 Style= csDropDownList

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ItemHeight= 14

 ParentFont= False

 TabOrder= 0

 end

 objectchfam_Edit: TEdit

 Left= 101

 Top= 90

 Width= 162

 Height= 22

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 1

 Text= 'chfam_Edit'

 end

 objectchname_Edit: TEdit

 Left= 101

 Top= 140

 Width= 162

 Height= 22

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 2

 Text= 'chname_Edit'

 end

 objectchgrand_Edit: TEdit

 Left= 101

 Top= 190

 Width= 162

 Height= 22

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 3

 Text= 'chgrand_Edit'

 end

 objectchadd_Button: TButton

 Left= 88

 Top= 294

 Width= 169

 Height= 25

 Hint= 'Новаязапись'

 Caption= '&Додати'

 ParentShowHint= False

 ShowHint= True

 TabOrder= 5

 OnClick= chadd_ButtonClick

 end

 objectchdelete_Button: TButton

 Left= 88

 Top= 322

 Width= 169

 Height= 25

 Hint= 'Удалениезаписи'

 Caption= '&Видалити'

 ParentShowHint= False

 ShowHint= True

 TabOrder= 6

 OnClick= chdelete_ButtonClick

 end

 objectchpost_Button: TButton

 Left= 88

 Top= 351

 Width= 169

 Height= 25

 Hint= 'Фиксацияизменений'

 Caption= '&Поновити'

 ParentShowHint= False

 ShowHint= True

 TabOrder= 7

 OnClick= chpost_ButtonClick

 end

 objectchyear_CSpinEdit: TCSpinEdit

 Left= 119

 Top= 233

 Width= 50

 Height= 23

 TabStop= True

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clBlack

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 MaxValue= 2000

 MinValue= 1900

 ParentColor= False

 ParentFont= False

 TabOrder= 8

 Value= 1950

 end

 end

 end

 objectleft_Panel: TPanel

 Left= 0

 Top= 0

 Width= 421

 Height= 429

 Align= alLeft

 BevelInner= bvLowered

 Caption= 'left_Panel'

 TabOrder= 1

 objectfind_TPanel: TPanel

 Left= 6

 Top= 5

 Width= 406

 Height= 420

 Caption= 'find_TPanel'

 TabOrder= 1

 objectfind_Label: TLabel

 Left= 109

 Top= 16

 Width= 265

 Height= 24

 Alignment= taCenter

 Caption= 'ПОШУКСПІВРОБІТНИКІВ'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clRed

 Font.Height= -21

 Font.Name= 'Arial Cyr'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 end

 objectdp_GroupBox: TGroupBox

 Left= 8

 Top= 48

 Width= 393

 Height= 65

 Caption= ' Відділок'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 0

 objectdp_ComboBox: TComboBox

 Left= 14

 Top= 22

 Width= 155

 Height= 24

 ItemHeight= 16

 Items.Strings= (

 'Бухгалтерия')

 TabOrder= 0

 OnChange= dp_ComboBoxChange

 end

 end

 objectdp2_GroupBox: TGroupBox

 Left= 216

 Top= 58

 Width= 169

 Height= 46

 Caption= ' підрозділ'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsItalic]

 ParentFont= False

 TabOrder= 1

 objectdp2_DBEdit: TDBEdit

 Left= 5

 Top= 15

 Width= 156

 Height= 23

 Color= clSilver

 DataField= 'PROISV'

 DataSource= dp_DataSource

 Enabled= False

 TabOrder= 0

 end

 end

 objectpr_GroupBox: TGroupBox

 Left= 8

 Top= 113

 Width= 393

 Height= 226

 Caption= ' Співробітники'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 2

 objectpr_Panel: TPanel

 Left= 9

 Top= 196

 Width= 66

 Height= 26

 TabOrder= 0

 objectpr_Label: TLabel

 Left= 9

 Top= 3

 Width= 47

 Height= 20

 Alignment= taCenter

 AutoSize= False

 Caption= '1'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clRed

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 Layout= tlCenter

 end

 end

 end

 objectfind_Animate: TAnimate

 Left= 40

 Top= 4

 Width= 48

 Height= 45

 Active= True

 CommonAVI= aviFindComputer

 StopFrame= 8

 end

 objectGroupBox1: TGroupBox

 Left= 8

 Top= 340

 Width= 393

 Height= 77

 Caption= 'ПоточнийоператорSQL'

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentFont= False

 TabOrder= 4

 objectsql_Label: TLabel

 Left= 11

 Top= 16

 Width= 372

 Height= 57

 AutoSize= False

 Color= clBtnFace

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clRed

 Font.Height= -13

 Font.Name= 'Times New Roman'

 Font.Style= [fsBold, fsItalic]

 ParentColor= False

 ParentFont= False

 WordWrap= True

 end

 end

 end

 objectpr_DBGrid: TDBGrid

 Left= 22

 Top= 136

 Width= 378

 Height= 173

 DataSource= pr_DataSource

 Font.Charset= RUSSIAN_CHARSET

 Font.Color= clWindowText

 Font.Height= -11

 Font.Name= 'Times New Roman'

 Font.Style= [fsItalic]

 Options= [dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs,dgConfirmDelete, dgCancelOnExit]

 ParentFont= False

 TabOrder= 0

 TitleFont.Charset= RUSSIAN_CHARSET

 TitleFont.Color= clWindowText

 TitleFont.Height= -11

 TitleFont.Name= 'Times New Roman'

 TitleFont.Style= [fsItalic]

 OnCellClick= pr_DBGridCellClick

 OnKeyDown= pr_DBGridKeyDown

 Columns= <

 item

 Expanded= False

 FieldName= 'FAM'

 Title.Caption= 'Прізвище'

 Width= 59

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'NAM'

 Title.Caption= 'ім'#39'я'

 Width= 57

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'PAR'

 Title.Caption= 'побатькові'

 Width= 67

 Visible= True

 end

 item

 Alignment= taCenter

 Expanded= False

 FieldName= 'YEAR_B'

 Title.Caption= 'рікнародження'

 Width= 85

 Visible= True

 end

 item

 Alignment= taCenter

 Expanded= False

 FieldName= 'SEX'

 Title.Caption= 'стать'

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'AGE'

 Title.Caption= 'вік'

 Width= 38

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'CHARACT'

 Title.Caption= 'характеристика'

 Visible= True

 end

 item

 Expanded= False

 FieldName= 'PHOTO'

 Title.Caption= 'фото'

 Visible= True

 end>

 end

 objectpr_DBNavigator: TDBNavigator

 Left= 96

 Top= 320

 Width= 304

 Height= 18

 DataSource= pr_DataSource

 VisibleButtons= [nbFirst, nbPrior, nbNext, nbLast]

 TabOrder= 2

 end

 end

 objectdp_DataSource: TDataSource

 DataSet= dp_Query

 Left= 110

 Top= 58

 end

 objectpr_DataSource: TDataSource

 DataSet= pr_Query

 Left= 213

 Top= 263

 end

 objectdp_Query: TQuery

 DatabaseName= 'dbP'

 RequestLive= True

 SQL.Strings= (

 'Select* from Dep where DEP = :PDEP')

 Left= 139

 Top= 58

 ParamData= <

 item

 DataType= ftString

 Name= 'PDEP'

 ParamType= ptUnknown

 end>

 objectdp_QueryDEP: TStringField

 FieldName= 'DEP'

 Origin= 'DEP.DEP'

 Size= 15

 end

 objectdp_QueryPROISV: TStringField

 FieldName= 'PROISV'

 Origin= 'DEP.PROISV'

 Size= 15

 end

 end

 objectupdate_Query: TQuery

 DatabaseName= 'dbP'

 DataSource= pr_DataSource

 RequestLive= True

 Left= 271

 Top= 263

 end

 objectpr_Query: TQuery

 ObjectView= True

 BeforePost= pr_QueryBeforePost

 AfterScroll= pr_QueryAfterScroll

 OnCalcFields= pr_QueryCalcFields

 DatabaseName= 'dbP'

 RequestLive= True

 SQL.Strings= (

 'Select* from Pers where DEP = :DEP order by FAM,NAM,PAR')

 Left= 242

 Top= 263

 ParamData= <

 item

 DataType= ftString

 Name= 'DEP'

 ParamType= ptUnknown

 end>

 objectpr_QueryNUM: TSmallintField

 FieldName= 'NUM'

 Origin= 'PERS.NUM'

 end

 objectpr_QueryDEP: TStringField

 FieldName= 'DEP'

 Origin= 'PERS.DEP'

 Size= 15

 end

 objectpr_QueryFAM: TStringField

 FieldName= 'FAM'

 Origin= 'PERS.FAM'

 end

 objectpr_QueryNAM: TStringField

 FieldName= 'NAM'

 Origin= 'PERS.NAM'

 end

 objectpr_QueryPAR: TStringField

 FieldName= 'PAR'

 Origin= 'PERS.PAR'

 end

 objectpr_QueryYEAR_B: TSmallintField

 FieldName= 'YEAR_B'

 Origin= 'PERS.YEAR_B'

 end

 objectpr_QuerySEX: TStringField

 FieldName= 'SEX'

 Origin= 'PERS.SEX'

 Size= 1

 end

 objectpr_QueryAGE: TSmallintField

 Alignment= taCenter

 DisplayLabel= 'Возраст'

 DisplayWidth= 7

 FieldKind= fkCalculated

 FieldName= 'AGE'

 Calculated= True

 end

 end

 objectinsert_StoredProc: TStoredProc

 ObjectView= True

 DatabaseName= 'dbP'

 StoredProcName= 'INSERTDBP'

 Left= 308

 Top= 263

 ParamData= <

 item

 DataType= ftString

 Name= 'PDEP'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PFAM'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PNAM'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PPAR'

 ParamType= ptInput

 end

 item

 DataType= ftInteger

 Name= 'PYEAR_B'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PSEX'

 ParamType= ptInput

 end>

 end

 objectupdate_StoredProc: TStoredProc

 ObjectView= True

 DatabaseName= 'dbP'

 StoredProcName= 'UPDATEDBP'

 Left= 366

 Top= 263

 ParamData= <

 item

 DataType= ftString

 Name= 'PDEP'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PFAM'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PNAM'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PPAR'

 ParamType= ptInput

 end

 item

 DataType= ftInteger

 Name= 'PYEAR_B'

 ParamType= ptInput

 end

 item

 DataType= ftString

 Name= 'PSEX'

 ParamType= ptInput

 end

 item

 DataType= ftInteger

 Name= 'NUMBER'

 ParamType= ptOutput

 end>

 end

 objectdelete_StoredProc: TStoredProc

 ObjectView= True

 DatabaseName= 'dbP'

 StoredProcName= 'DELETEDBP'

 Left= 337

 Top= 263

 ParamData= <

 item

 DataType= ftInteger

 Name= 'PNUM'

 ParamType= ptInput

 end>

 end

end

Дляфункціонуванняприкладеннярозробленопрограму:

ФайлUdb.h

//---------------------------------------------------------------------------

#ifndefUdbH

#defineUdbH

//---------------------------------------------------------------------------

#include<Classes.hpp>

#include<Controls.hpp>

#include<StdCtrls.hpp>

#include<Forms.hpp>

#include<ComCtrls.hpp>

#include<DBCtrls.hpp>

#include<DBGrids.hpp>

#include<ExtCtrls.hpp>

#include<Grids.hpp>

#include<Mask.hpp>

#include<Db.hpp>

#include<DBTables.hpp>

#include«cspin.h»

#include«CSPIN.h»

#include<jpeg.hpp>

#include<Buttons.hpp>

#include<Graphics.hpp>

//---------------------------------------------------------------------------

classTmain_Form: public TForm

{

__published:        //IDE-managed Components

 TPageControl*PageControl;

 TTabSheet*find_TabSheet;

 TRadioGroup*sex_RadioGroup;

 TEdit*speedfind_Edit;

 TDataSource*dp_DataSource;

 TDataSource*pr_DataSource;

         TTabSheet*TabEdit;

 TComboBox*chdp_ComboBox;

 TEdit*chfam_Edit;

 TEdit*chname_Edit;

 TEdit*chgrand_Edit;

 TRadioGroup*sex2_RadioGroup;

 TButton*chadd_Button;

 TButton*chdelete_Button;

 TButton*chpost_Button;

 TCSpinEdit*chyear_CSpinEdit;

 TCSpinEdit*minage_CSpinEdit;

 TCSpinEdit*maxage_CSpinEdit;

 TPanel*left_Panel;

 TPanel*find_TPanel;

 TLabel*find_Label;

 TGroupBox*dp_GroupBox;

 TGroupBox*dp2_GroupBox;

 TGroupBox*pr_GroupBox;

 TDBGrid*pr_DBGrid;

 TDBNavigator*pr_DBNavigator;

 TGroupBox*ch_GroupBox;

 TLabel*chdp_Label;

 TLabel*chname_Label;

 TLabel*chgrand_Label;

 TLabel*chyear_Label;

 TLabel*chfam_Label;

 TGroupBox*age_GroupBox;

 TLabel*minage_Label;

 TLabel*maxage_Label;

 TGroupBox*speedfind_GroupBox;

 TLabel*speedfind_Label;

 TImage*speedfind_Image;

 TImage*minage_Image;

 TImage*maxage_Image;

 TAnimate*find_Animate;

 TBitBtn*select_BitBtn;

 TGroupBox*select_GroupBox;

 TQuery*dp_Query;

 TQuery*update_Query;

 TComboBox*dp_ComboBox;

 TDBEdit*dp2_DBEdit;

 TStringField*dp_QueryDEP;

 TStringField*dp_QueryPROISV;

 TGroupBox*GroupBox1;

 TLabel*sql_Label;

 TAnimate*Animate1;

 TBevel*oper_Bevel;

 TShape*oper_Shape;

 TImage*Image1;

 TQuery*pr_Query;

 TSmallintField*pr_QueryNUM;

 TStringField*pr_QueryDEP;

 TStringField*pr_QueryFAM;

 TStringField*pr_QueryNAM;

 TStringField*pr_QueryPAR;

 TSmallintField*pr_QueryYEAR_B;

 TStringField*pr_QuerySEX;

 TSmallintField*pr_QueryAGE;

 TStoredProc*insert_StoredProc;

 TStoredProc*update_StoredProc;

 TStoredProc*delete_StoredProc;

 TPanel*pr_Panel;

 TLabel*pr_Label;

void__fastcall FormCreate(TObject *Sender);

void__fastcall dp_ComboBoxChange(TObject *Sender);

void__fastcall speedfind_EditChange(TObject *Sender);

void__fastcall pr_QueryCalcFields(TDataSet *DataSet);

void__fastcall pr_QueryAfterScroll(TDataSet *DataSet);

void__fastcall pr_QueryBeforePost(TDataSet *DataSet);

void__fastcall chadd_ButtonClick(TObject *Sender);

void__fastcall chdelete_ButtonClick(TObject *Sender);

void__fastcall chpost_ButtonClick(TObject *Sender);

void__fastcall PageControlChange(TObject *Sender);

 void__fastcall minage_CSpinEditChange(TObject *Sender);

 void__fastcall select_BitBtnClick(TObject *Sender);

 void__fastcall pr_DBGridCellClick(TColumn *Column);

 void__fastcall prview_RadioGroupClick(TObject *Sender);

 void__fastcall pr_DBGridKeyDown(TObject *Sender, WORD &Key,

 TShiftStateShift);

private://User declarations

public://User declarations

fastcallTmain_Form(TComponent* Owner);

 unsignedshort Year;

 unsignedshort Month;

 unsignedshort Day;

 boolCanPost;

 AnsiStringsql_Operator;

 void__fastcall Delay(unsigned long int mSeconds);

};

//---------------------------------------------------------------------------

externPACKAGE Tmain_Form *main_Form;

//---------------------------------------------------------------------------

#endif

ФайлUdb.cpp

#include<vcl.h>

#pragmahdrstop

#include«Udb.h»

#pragmapackage(smart_init)

#pragmalink «cspin»

#pragmalink «CSPIN»

#pragmaresource "*.dfm"

Tmain_Form*main_Form;

fastcallTmain_Form::Tmain_Form(TComponent* Owner)

 TForm(Owner)

{}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::FormCreate(TObject *Sender)

{

 CanPost= false;

 Date().DecodeDate(&Year,&Month,&Day);

 pr_Query->SQL->Clear();

 sql_Operator= «Select * from PERS order by NUM»;

 sql_Label->Caption= sql_Operator;

 pr_Query->SQL->Add(sql_Operator);

 pr_Query->Open();

 pr_Query->First();

 dp_Query->SQL->Clear();

 sql_Operator= «Select * from DEP»;

 sql_Label->Caption= sql_Operator;

 dp_Query->SQL->Add(sql_Operator);

 dp_Query->Open();

 dp_Query->First();

 //ЗаповненняComboBox dp_ComboBox таchdp_ComboBox наймуваннями відділків

 dp_ComboBox->Clear();

 chdp_ComboBox->Clear();

 while(!dp_Query->Eof) {

 dp_ComboBox->Items->Add(dp_QueryDEP->AsString);

 chdp_ComboBox->Items->Add(dp_QueryDEP->AsString);

 dp_Query->Next();

 }

 dp_ComboBox->Items->Add(«усівідділки»);

 dp_ComboBox->ItemIndex= dp_ComboBox->Items->Count — 1;

 dp_ComboBoxChange(Sender);

 chdp_ComboBox->ItemIndex= dp_ComboBox->ItemIndex;

 PageControl->ActivePage= find_TabSheet;

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::dp_ComboBoxChange(TObject *Sender)

{

 dp_Query->Close();

 dp_Query->SQL->Clear();

 sql_Operator= «Select * from DEP where DEP=:PDEP»;

 sql_Label->Caption= sql_Operator;

 Delay(3000);

 dp_Query->SQL->Add(sql_Operator);

 dp_Query->Params->Items[0]->AsString= dp_ComboBox->Text;

 dp_Query->Open();

 dp_Query->First();

 pr_Query->Close();

 pr_Query->SQL->Clear();

 if(dp_ComboBox->ItemIndex == dp_ComboBox->Items->Count — 1) {

 //показвсіхзаписів

 sql_Operator= «Select * from PERS order by NUM»;

 sql_Label->Caption= sql_Operator;

 Delay(3000);

 pr_Query->SQL->Add(sql_Operator);

 }else {

 // показ записів запереглядами

 sql_Operator=

 «Select* from DEP_» + AnsiString(dp_ComboBox->ItemIndex + 1);

 sql_Label->Caption= sql_Operator;

 Delay(3000);

 pr_Query->SQL->Add(sql_Operator);

 }

 pr_Query->ExecSQL();

 pr_Query->Open();

 pr_Query->First();

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::speedfind_EditChange(TObject *Sender)

{

 TLocateOptionsSearchOptions;

 pr_Query->Locate(«FAM»,speedfind_Edit->Text,

 SearchOptions<< loPartialKey << loCaseInsensitive);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::pr_QueryCalcFields(TDataSet *DataSet)

{

 pr_QueryAGE->Value= Year — pr_QueryYEAR_B->Value;

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::pr_QueryAfterScroll(TDataSet *DataSet)

{

 if(PageControl->ActivePage == TabEdit) {

 //відображенняданихпропоточнуперсону

 chdp_ComboBox-> ItemIndex =

 chdp_ComboBox->Items->IndexOf(pr_QueryDEP->AsString);

 chfam_Edit->Text= pr_QueryFAM->AsString;

 chname_Edit->Text= pr_QueryNAM->AsString;

 chgrand_Edit->Text= pr_QueryPAR->AsString;

 chyear_CSpinEdit->Value= pr_QueryYEAR_B->AsInteger;

 if(pr_QuerySEX->AsString == «ч»)sex2_RadioGroup->ItemIndex = 0;

 elsesex2_RadioGroup->ItemIndex = 1;

 }

 pr_Label->Caption= pr_QueryNUM->AsString;

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::pr_QueryBeforePost(TDataSet *DataSet)

{

 if(!CanPost) {

 DataSet->Cancel();

 Abort;

 }

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::chadd_ButtonClick(TObject *Sender)

{// додаваннязаписудотаблиціPERS

 insert_StoredProc->ParamByName(«pDEP»)->AsString= chdp_ComboBox->Text;

 insert_StoredProc->ParamByName(«pFAM»)->AsString= chfam_Edit->Text;

 insert_StoredProc->ParamByName(«pNAM»)->AsString= chname_Edit->Text;

 insert_StoredProc->ParamByName(«pPAR»)->AsString= chgrand_Edit->Text;

 insert_StoredProc->ParamByName(«pYEAR_B»)->AsInteger= chyear_CSpinEdit->Value;

 insert_StoredProc->ParamByName(«pSEX»)->AsString=

 sex2_RadioGroup->Items->Strings[sex2_RadioGroup->ItemIndex];

 sql_Operator=

 «Insertinto PERS (DEP, FAM, NAM, PAR, YEAR_B, SEX)»

 "VALUES (:pDEP, :pFAM, :pNAM, :pPAR, :pYEAR_B, :pSEX)";

 sql_Label->Caption= sql_Operator;

 insert_StoredProc->Prepare();

 insert_StoredProc->ExecProc();

 dp_ComboBoxChange(Sender);

 ShowMessage(«ВставкузаписузбереженоюпроцедуроюINSERTdbP виконано успішно!»);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::chdelete_ButtonClick(TObject *Sender)

{ // видаленняпоточного запису з таблиці PERS

 if(Application->MessageBox(«Ви дійсно бажаєте видалити поточнийзапис?»,

 «Підтвердітьвидалення запису»,

 MB_YESNO +MB_ICONEXCLAMATION) == IDYES) {

 delete_StoredProc->ParamByName(«pNUM»)->AsInteger=

 pr_QueryNUM->AsInteger;

 sql_Operator= «Delete from PERS where NUM = :pNUM»;

 sql_Label->Caption= sql_Operator;

 delete_StoredProc->Prepare();

 delete_StoredProc->ExecProc();

 dp_ComboBoxChange(Sender);

 ShowMessage(«ВидаленнязаписузбереженоюпроцедуроюDELETEdbP виконано успішно!»);

 }

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::chpost_ButtonClick(TObject *Sender)

{

 update_StoredProc->ParamByName(«pDEP»)->AsString= chdp_ComboBox->Text;

 update_StoredProc->ParamByName(«pFAM»)->AsString= chfam_Edit->Text;

 update_StoredProc->ParamByName(«pNAM»)->AsString= chname_Edit->Text;

 update_StoredProc->ParamByName(«pPAR»)->AsString= chgrand_Edit->Text;

 update_StoredProc->ParamByName(«pYEAR_B»)->AsInteger= chyear_CSpinEdit->Value;

 update_StoredProc->ParamByName(«pSEX»)->AsString=

 sex2_RadioGroup->Items->Strings[sex2_RadioGroup->ItemIndex];

 sql_Operator=

 «UpdatePERS Set DEP = :pDEP, YEAR_B = :pYEAR_B, SEX = :pSEX „

 “Where (FAM = :pFAM) and (NAM = :pNAM) and (PAR = :pPAR)»;

 sql_Label->Caption= sql_Operator;

 update_StoredProc->Prepare();

 update_StoredProc->ExecProc();

 dp_ComboBoxChange(Sender);

 if(update_StoredProc->ParamByName(«NUMBER»)->AsInteger == 0)

 ShowMessage("* Помилка поновленнязапису!");

 else

 ShowMessage(«Поновленнязаписузбережено.процедуроюUPDATEdbP виконано успішно!»);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::PageControlChange(TObject *Sender)

{

 if(PageControl->ActivePage == TabEdit)

 pr_QueryAfterScroll(pr_Query);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::minage_CSpinEditChange(TObject *Sender)

{

 AnsiStrings =

 "(YEAR_B<="+ IntToStr(int(Year — minage_CSpinEdit->Value)) +

 ")and(YEAR_B>="+ IntToStr(int(Year — maxage_CSpinEdit->Value)) +

 ")and(SEX=";

 if(!sex_RadioGroup->ItemIndex) s += "'ч')";

 elses += "'ж')";

 // автоматичнепоновлення відбору записів

 select_BitBtn->Kind= bkCancel;

 select_BitBtn->Caption= «Відмінитивідбір»;

 pr_Query->Filter= s;

 pr_Query->Filtered= true;

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::select_BitBtnClick(TObject *Sender)

{

 if(pr_Query->Filtered) { // відмінарежимуфільтрації

 pr_Query->Filtered= false;

 select_BitBtn->Kind= bkYes;

 select_BitBtn->Caption= «Поновитивідбір»;

 }else { // встановлення режимуфільтрації

 select_BitBtn->Kind= bkCancel;

 select_BitBtn->Caption= «Відмінитивідбір»;

 minage_CSpinEditChange(Sender);

 }

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::pr_DBGridCellClick(TColumn *Column)

{

 if(PageControl->ActivePage == TabEdit) {

 chdp_ComboBox-> ItemIndex =

 chdp_ComboBox->Items->IndexOf(pr_QueryDEP->AsString);

 chfam_Edit->Text= pr_QueryFAM->AsString;

 chname_Edit->Text= pr_QueryNAM->AsString;

 chgrand_Edit->Text= pr_QueryPAR->AsString;

 chyear_CSpinEdit->Value= pr_QueryYEAR_B->AsInteger;

 if(pr_QuerySEX->AsString == «ч»)sex2_RadioGroup->ItemIndex = 0;

 elsesex2_RadioGroup->ItemIndex = 1;

 }

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::Delay(unsigned long int mSeconds)

{// затримканадекількамілісекунд

 unsignedlong int FirstTick;

 FirstTick= GetTickCount();

 do

 Application->ProcessMessages();

 while(GetTickCount() — FirstTick <= mSeconds);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::prview_RadioGroupClick(TObject *Sender)

{

 dp_ComboBoxChange(Sender);

}

//---------------------------------------------------------------------------

void__fastcall Tmain_Form::pr_DBGridKeyDown(TObject *Sender, WORD &Key,

 TShiftStateShift)

{

 pr_Label->Caption= pr_QueryNUM->AsString;

}

//---------------------------------------------------------------------------

Длявиконанняприкладеннятребапопередньозавантажитинавиконанняприкладення-серверIBServer.EXE, яке зазвичайзнаходитьсязамаршрутом«E:\Program Files\InterBase Corp\InterBase\Bin\» іобслуговуєзапитидобазиданихInterbase. Після завантаження поточ-ного проекту на виконанняцей сервер виводить на екран запит (мал… 1.21), у полі Password: якого требаввести пароль доступу masterkey.:

/>

Малюнок 1.21

Приклад вигляду формипід час функціонування прикладення наведено на мал. 1.22.

/>

 Малюнок 1.22


Контрольнi запитання:

1.      Детальноопишіть компоненти RAD: TDataSource,TQuery, TDBMemo,TDBGrid, TDBImage,TDBText, TDBNavigator,TStoredProc.

2.      Якстворити БД Interbase і призначити їй аліас?

3.      Якстворити індекси таблиці БД Interbase?

4.      Якстворити і використати у прикладенні перегляд таблиці БД Interbase?

5.      Якимчином створюється і для чого використовується генератор БД Interbase?

6.      Якпризначити зв’язок компонентів з реальною БД?

7.      Якимчином створюється і для чого використовується триггер БД Interbase?

8.      Якимчином створюється і для чого використовується збережена процедура БДInter-base?

9.      Длячого використовується оператор SQL “SELECT”, наприклад:

 «Select* from DEP where DEP=:PDEP»?

10.    Опишітьметодику додавання і видалення запису до/з таблиці БД. Чому для цього використовуєтьсядодатковий компонент TQuery?

11.    Опишітьметодику додавання, видалення і корегування записів таблиці БД ізвикорис-танням збережених процедур.

12.    Дайтедокладні пояснення до розробленої програми.

еще рефераты
Еще работы по информатике, программированию