|
Создание базы данных
344End With2345End Sub23462347' удаление записи2348Public Sub DelRow_(DBIndex%, Optional ByVal Index% = - 1, Optional ByVal conf As Boolean = True) 2349 With DB(DBIndex). Header2350 If (. RowCount = 0) Then Exit Sub2351 If (Index = - 1) Then Index =. RowCount - 12352 If (Index >. RowCount - 1) Then2353 Call MsgForm. ErrorMsg("Ошибка удаления записи! ") 2354 Exit Sub2355 End If2356 2357 If conf Then2358 If (MsgForm. QuestMsg("Удалить запись? ") = resNo) Then Exit Sub2359 End If2360 For i% = Index To (. RowCount - 2) 2361 DB(DBIndex). Rows(i) = DB(DBIndex). Rows(i + 1) 2362 Next i2363. RowCount =. RowCount - 12364 ReDim Preserve DB(DBIndex). Rows(. RowCount) 2365 DBChanged = True2366End With2367End Sub23682369Public Sub TestDBChanged() 2370 If DBChanged Then2371 MainForm. SB. Panels(1). Picture = MainForm. ImageList1. ListImages(2). Picture2372 Else2373 Set MainForm. SB. Panels(1). Picture = Nothing2374 End If2375End Sub23762377' отображение таблицы2378Public Sub ShowTable(DBIndex%) 2379 MainForm. ListView. ListItems. Clear2380 MainForm. ListView. ColumnHeaders. Clear2381 If (DBIndex = - 1) Then2382 DBPath = ""2383 MainForm. SB. Panels(3). Text = ""2384 GoTo exit_2385 End If2386 If (DB(DBIndex). Header. ColCount = 0) Then GoTo exit_2387 For c% = 0 To DB(DBIndex). Header. ColCount - 12388 Call MainForm. ListView. ColumnHeaders. Add(_2389 MainForm. ListView. ColumnHeaders. Count + 1, _2390 "col_key_" + CStr(c), _2391 DB(DBIndex). Cols(c). title, _2392 1440, _2393 lvwColumnLeft, _2394 0 _2395) 23962397 Next c2398 For R% = 0 To DB(DBIndex). Header. RowCount - 12399 With MainForm. ListView. ListItems. Add2400. Key = "row_key_" + CStr(R) 2401. Text = DB(DBIndex). Rows(R). Fields(0) 2402 For i% = 1 To DB(DBIndex). Header. ColCount - 12403. SubItems(i) = DB(DBIndex). Rows(R). Fields(i) 2404 Next i2405 End With2406 Next R2407exit_: 2408 MainForm. TabStrip. Visible = (DBPath <> "") 2409 MainForm. ListView. Visible = MainForm. TabStrip. Visible2410 If (DBIndex <> - 1) Then2411 MainForm. SB. Panels(2). Text = CStr(DB(DBIndex). Header. RowCount) 2412 Else2413 MainForm. SB. Panels(2). Text = ""2414 End If2415 Call TestDBChanged2416End Sub24172418' поиск поля *************************************************2419Public Function ItColAlreadyCreate(QRDBIndex%, title$) As Boolean2420 With DB(QRDBIndex) 2421 For i% = 0 To (DB(QRDBIndex). Header. ColCount - 1) 2422 If (. Cols(i). title = title) Then2423 ItColAlreadyCreate = True2424 Exit Function2425 End If2426 Next i2427 End With2428 ItColAlreadyCreate = False2429End Function24302431' добавление поля *************************************************2432Public Sub AddCol(DBIndex%, ByVal Class%, ByVal title$, ByVal defval, Optional ByVal pos% = - 1) 2433 With DB(DBIndex). Header2434 ReDim Preserve DB(DBIndex). Cols(. ColCount) 2435 If (pos = - 1) Then2436 pos =. ColCount2437 Else2438 For i% = 1 To (. ColCount - pos) 2439 DB(DBIndex). Cols(. ColCount - i + 1) = DB(DBIndex). Cols(. ColCount - i) 2440 Next i2441 End If2442 With DB(DBIndex). Cols(pos) 2443. Class = Class2444. title = title2445. TitleLen = Len(title) 2446. DefValue = defval2447 End With2448 2449 ' увеличиваю размерность записей2450 For R% = 0 To DB(DBIndex). Header. RowCount - 12451 ReDim Preserve DB(DBIndex). Rows(R). Fields(. ColCount) 2452 For i% = 1 To (. ColCount - pos) 2453 DB(DBIndex). Rows(R). Fields(. ColCount - i + 1) = DB(DBIndex). Rows(R). Fields(. ColCount - i) 2454 Next i2455 DB(DBIndex). Rows(R). Fields(pos) = DB(DBIndex). Cols(pos). DefValue2456 Next R2457 2458. ColCount =. ColCount + 12459 2460 DBChanged = True2461 End With2462End Sub24632464' добавление записи *************************************************2465Public Sub AddField(DBIndex%, row) 2466 With DB(DBIndex). Header2467 ReDim Preserve DB(DBIndex). Rows(. RowCount) 2468 DB(DBIndex). Rows(. RowCount). Fields = row2469. RowCount =. RowCount + 12470 DBChanged = True2471 End With2472End Sub24732474' удаление таблицы *************************************************2475Public Sub DelTable(Index%) 2476 For i% = Index To (UBound(DB) - 1) 2477 DB(i) = DB(i + 1) 2478 Next i2479 If (UBound(DB) > 0) Then ReDim Preserve DB(UBound(DB) - 1) 2480End Sub24812482' если нужно то строка шифруется по паролю, иначе не изменяется2483Function CodeDecode(Index%, str$, col%, row%, Optional pass$ = "", Optional usepass As Boolean = False) As String2484 If Not usepass Then pass$ = DB(Index). Password2485 If (pass = "") Then2486 CodeDecode = str2487 Exit Function2488 End If2489 CodeDecode = ""2490 p% = 12491 Dim ch As Byte2492 For i% = 1 To Len(str) 2493 ch = Asc(Mid(str, i, 1)) Xor Asc(Mid(pass, p, 1)) Xor col Xor row2494 CodeDecode = CodeDecode + Chr(ch) 2495 p = p + 1: If p > Len(pass) Then p = 12496 Next i2497End Function24982499' сохранение БД в файле *************************************************2500Public Sub FlushDB(DBIndex%) 2501 Dim s$, W%2502 If Not UserIsAdmin Then2503 Call ProtectedMsg2504 Exit Sub2505 End If2506 If (DBPath <> "") Then2507 Call DeleteFile(DBPath) 2508 DBI% = FreeFile2509 Open DBPath For Binary As DBI2510 2511 ' заголовок - 122512 Put DBI,, DB(DBIndex). Header2513 2514 ' если надо, то сохраняю пароль2515 If (DB(DBIndex). Header. Flags And flPasswordNeed) Then2516 Dim str$, ch1 As Byte, ch2 As Byte2517 Dim lng As Byte, lng2 As Byte2518 lng = Len(DB(DBIndex). Password) 2519 lng2 = lng / 22520 Put DBI,, lng2521 2522 For i% = 1 To lng22523 ch1 = Asc(Mid(DB(DBIndex). Password, i, 1)) 2524 ch2 = Asc(Mid(DB(DBIndex). Password, lng - i + 1, 1)) 2525 str = Chr(ch1 Xor ch2) + str2526 Next i2527 For i = lng2 To 1 Step - 12528 Put DBI,, CByte(Asc(Mid(str, i, 1))) 2529 Next i2530 End If ' сохранение пароля2531 2532 ' данные полей2533 Dim l As Long2534 For i% = 0 To DB(DBIndex). Header. ColCount - 12535 Put DBI,, DB(DBIndex). Cols(i). Class2536 Put DBI,, DB(DBIndex). Cols(i). TitleLen2537 If (DB(Index). Header. Flags And flCoded) Then2538 Put DBI,, CodeDecode(DBIndex, DB(DBIndex). Cols(i). title, i, 0) 2539 Else2540 Put DBI,, DB(DBIndex). Cols(i). title2541 End If2542 Select Case DB(DBIndex). Cols(i). Class2543 Case ccString2544 If (DB(Index). Header. Flags And flCoded) Then2545 s = CodeDecode(DBIndex, CStr(DB(DBIndex). Cols(i). DefValue), i, 0) 2546 Else2547 s = CStr(DB(DBIndex). Cols(i). DefValue) 2548 End If2549 W = Len(s) 2550 Put DBI,, W2551 Put DBI,, s2552 Case ccInteger2553 l = CInt(DB(DBIndex). Cols(i). DefValue) 2554 Put DBI,, l2555 End Select2556 Next i2557 2558 ' запись контрольного байта2559 Put DBI,, ValidateByte2560 2561 ' записи2562 Dim f As TDBElem2563 Dim col As TDBElemData2564 For R% = 0 To DB(DBIndex). Header. RowCount - 12565 f = DB(DBIndex). Rows(R) 2566 For c% = 0 To DB(DBIndex). Header. ColCount - 12567 col = DB(DBIndex). Cols(c) 2568 ' в зависимости от типа данных колонки пишу в файл определённый тип данных2569 Select Case col. Class2570 ' если число - записываю как long2571 Case ccInteger2572 l = CLng(f. Fields(c)) 2573 Put DBI,, l2574 ' если строка - то байт длины и сама строка2575 Case ccString2576 If (DB(Index). Header. Flags And flCoded) Then2577 s = CodeDecode(DBIndex, CStr(f. Fields(c)), c, R) 2578 Else2579 s = CStr(f. Fields(c)) 2580 End If2581 ' Len возвращает 4 байта, а мне нужно 22582 W = Len(s) 2583 Put DBI,, W2584 Put DBI,, s2585 End Select2586 Next c2587 Next R2588 2589 MainForm. SB. Panels(3). Text = DBPath2590 Call MsgForm. InfoMsg("БД сохранена! ") 2591 2592 ' закрытие файла2593 Close2594 DBChanged = False2595 Call TestDBChanged2596 End If2597End Sub25982599' загрузка БД *************************************************2600Public Function LoadDB(DBIndex%, ByVal Path$) As Boolean2601 Dim DBH As TDBHeader2602 pwrd$ = ""2603 LoadDB = False2604 DBI% = FreeFile2605 DBP$ = Path2606 ' открываю БД2607 Open DBP For Binary As DBI2608 ' считываю заголовок2609 Get DBI,, DBH2610 With DBH2611 If (. Header <> "DBX") Then2612 Call MsgForm. ErrorMsg("БД повреждена! ") 2613 GoTo Notdata2614 End If26152616 ' если надо, то загружаю пароль2617 If (DBH. Flags And flPasswordNeed) Then2618 Dim lng As Byte2619 Get DBI,, lng2620 Dim str$, ch1 As Byte, ch2 As Byte, ch3 As Byte2621 str = ""2622 For i% = 1 To lng \ 22623 Get DBI,, ch12624 str = str + Chr(ch1) 2625 Next i2626'********************************************************2627 With PasswordForm2628. PassText = ""2629 2630. CaptionLabel = "Защита БД"2631. TextLabel = "Открываемая БД защищена паролем. Для работы с БД необходимо ввести пароль. "2632. Frame2. Visible = False2633. Frame1. Visible = True2634 2635 Dim ROE As Boolean2636 2637 ROE = Not ((DBH. Flags And flReadOnlyEnable) = flReadOnlyEnable) 2638 2639 If ROE Then2640. Frame3. Visible = True2641. NoFullLabel. Visible = False2642 Else2643. Frame3. Visible = False2644. NoFullLabel. Visible = True2645 End If2646. Show vbModal2647 If (. res) Then2648 ' допустимый тип доступа2649 Mode% = 02650 ' введёный пароль2651 str2$ = Trim(. PassText) 2652 2653 ' проверка пароля2654 lng_2 = Len(str2) 2655 If (lng_2 <> lng) Then2656 Mode = - 12657 GoTo bad2658 End If2659 For i% = 1 To lng \ 22660 ch1 = Asc(Mid(str2, i, 1)) 2661 ch2 = Asc(Mid(str2, lng - i + 1, 1)) 2662 ch3 = Asc(Mid(str, i, 1)) 2663 If ((ch1 Xor ch2) <> ch3) Then2664 Mode = - 12665 GoTo bad2666 End If2667 Next i2668 2669bad: 2670 ' обработка правильности пароля и уровня доступа2671 If (Mode = 0) And (. Check1 = 0) Then2672 Call MsgForm. InfoMsg("Пароль принят! ") 2673 pwrd = str22674 UserIsAdmin = True2675 Else2676 If ROE And (. Check1 = 1) Then2677 Call MsgForm. InfoMsg("Только чтение! ") 2678 UserIsAdmin = False2679 Else2680 Call MsgForm. ErrorMsg("Пароль не принят! Доступ запрещён! ") 2681 Unload PasswordForm2682 GoTo Notdata2683 End If2684 End If2685 Else2686 Unload PasswordForm2687 GoTo Notdata2688 End If ' if (. res) 2689 Unload PasswordForm2690 End With2691'********************************************************2692 End If26932694 ' выделение нужной памяти2695 If (. ColCount > 0) Then2696 ReDim DB(DBIndex). Cols(. ColCount - 1) 2697 If (. RowCount > 0) Then2698 ReDim DB(DBIndex). Rows(. RowCount - 1) 2699 For R% = 0 To. RowCount - 12700 ReDim DB(DBIndex). Rows(R). Fields(. ColCount - 1) 2701 Next R2702 End If2703 End If2704 2705 ' считывание данных полей2706 For i% = 0 To DBH. ColCount - 12707 ' получение класса2708 Get DBI,, DB(DBIndex). Cols(i). Class2709 ' получение длины заголовка2710 Get DBI,, DB(DBIndex). Cols(i). TitleLen2711 ' получение заголовка2712 s$ = ""2713 Dim B As Byte2714 For j% = 1 To DB(DBIndex). Cols(i). TitleLen2715 Get DBI,, B2716 s = s + Chr(B) 2717 Next j2718 s = CodeDecode(DBIndex, s, i, 0, pwrd, True) 2719 DB(DBIndex). Cols(i). title = s2720 ' получение значения по-умолчанию2721 Dim l As Long2722 Dim W%2723 Select Case DB(DBIndex). Cols(i). Class2724 Case ccInteger2725 Get DBI,, l2726 DB(DBIndex). Cols(i). DefValue = l2727 Case ccString2728 Get DBI,, W2729 s = ""2730 For j% = 1 To W2731 Get DBI,, B2732 s = s + Chr(B) 2733 Next j2734 s = CodeDecode(DBIndex, s, i, 0, pwrd, True) 2735 DB(DBIndex). Cols(i). DefValue = s2736 End Select2737 Next i2738 2739 ' чтение контрольного байта2740 Dim VB As Byte2741 Get DBI,, VB2742 If (VB <> ValidateByte) Then2743 Call MsgForm. ErrorMsg("БД повреждена! ") 2744 GoTo Notdata2745 End If27462747 ' считывание записей2748 Dim col As TDBElemData2749 For R% = 0 To. RowCount - 12750 For c% = 0 To. ColCount - 12751 col = DB(DBIndex). Cols(c) 2752 ' в зависимости от типа данных колонки пишу в файл определённый тип данных2753 Select Case col. Class2754 ' если число - считываю как long2755 Case ccInteger2756 Get DBI,, l2757 DB(DBIndex). Rows(R). Fields(c) = l2758 ' если строка - то байт длины и сама строка2759 Case ccString2760 Get DBI,, W2761 s = ""2762 For j% = 1 To W2763 Get DBI,, B2764 s = s + Chr(B) 2765 Next j2766 s = CodeDecode(DBIndex, s, c, R, pwrd, True) 2767 DB(DBIndex). Rows(R). Fields(c) = s2768 End Select2769 Next c2770 Next R2771 2772 End With2773 LoadDB = True2774 2775 DB(DBIndex). Header = DBH2776 DBPath = DBP2777 DBChanged = False2778 DB(DBIndex). Password = pwrd2779 2780 Call MsgForm. InfoMsg("БД загружена! ") 2781 2782Notdata: 2783 ' закрытие файла2784 Close2785End Function27862787' создание новой БД *************************************************2788Public Function NewDB(Path$) 2789 DBI% = FreeFile2790 ' удаляю БД2791 Call DeleteFile(Path) 2792 ' открываю БД2793 Open Path For Binary As DBI2794 ' применяю стандартный заголовок к БД2795 Call ClearAll2796 DBPath = Path2797 ' записываю заголовок БД2798 Put DBI,, DB(0). Header2799 ' запись контрольного байта2800 Put DBI,, ValidateByte2801 Close2802 Call MsgForm. InfoMsg("БД создана с настройками по-умолчанию! ") 2803End Function28042805' очистка ВСЕГО2806Public Sub ClearAll() 2807 ReDim DB(0) 2808 Call ClearHeader(DB(0). Header) 2809 DBChanged = False2810 DBPath = ""2811End Sub28122813' установка полей в начальные значения *************************************************2814Public Sub ClearHeader(H As TDBHeader) 2815 H. Header = "DBX"2816 H. Flags = 02817 H. ColCount = 02818 H. RowCount = 02819End SubМодуль: API. bas2820' создание файла2821Declare Function DeleteFile Lib "kernel32" Alias "DeleteFileA" (ByVal lpFileName As String) As Long28222823' создание архивной копии БД2824Public Declare Function CopyFile Lib "kernel32" Alias "CopyFileA" (ByVal lpExistingFileName As String, ByVal lpNewFileName As String, ByVal bFailIfExists As Long) As Long28252826' запуск браузера и почтовой программы2827Public Declare Function ShellExecute Lib "shell32. dll" Alias "ShellExecuteA" (ByVal hwnd As Long, ByVal lpOperation As String, ByVal lpFile As String, ByVal lpParameters As String, ByVal lpDirectory As String, ByVal nShowCmd As Long) As Long28282829' звук2830Public Declare Function sndPlaySound Lib "winmm. dll" Alias "sndPlaySoundA" (ByVal lpszSoundName As String, ByVal uFlags As Long) As Long2831Public Const SND_APPLICATION = &H802832Public Const SND_ASYNC = &H12833Public Const SND_FILENAME = &H2000028342835' перемещение окна и анимация кнопок2836Public Type RECT2837 Left As Long2838 Top As Long2839 Right As Long2840 Bottom As Long2841End Type2842Public Type POINTAPI2843 x As Long2844 y As Long2845End Type2846Public Declare Function GetWindowRect Lib "user32" (ByVal hwnd As Long, lpRect As RECT) As Long2847Public Declare Function MoveWindow Lib "user32" (ByVal hwnd As Long, ByVal x As Long, ByVal y As Long, ByVal nWidth As Long, ByVal nHeight As Long, ByVal bRepaint As Long) As Long2848Public Declare Function GetCursorPos Lib "user32" (lpPoint As POINTAPI) As Long2849Public Declare Function SetCursorPos Lib "user32" (ByVal x As Long, ByVal y As Long) As Long2850Public Declare Function PtInRect Lib "user32" (lpRect As RECT, pt As POINTAPI) As Long28512852' перетаскивание2853Dim ClickBool As Boolean2854Dim Xs%, Ys%28552856Sub MInit() 2857 ClickBool = False2858 Xs = 02859 Ys = 02860End Sub28612862Sub MMove(ByVal Handle As Long, ByVal x%, ByVal y%) 2863 Dim R As RECT2864 If ClickBool Then2865 Call GetWindowRect(Handle, R) 2866 W% = R. Right - R. Left2867 H% = R. Bottom - R. Top2868 x = R. Left + (x - Xs) / Screen. TwipsPerPixelX2869 y = R. Top + (y - Ys) / Screen. TwipsPerPixelY2870 Call MoveWindow(Handle, x, y, W, H, True) 2871 End If2872End Sub28732874Sub MDown(ByVal x%, ByVal y%) 2875 ClickBool = True2876 Xs = x2877 Ys = y2878End Sub28792880Sub MUp() 2881 ClickBool = False2882End SubМодуль: DBConst. bas2883' результаты работы диалогов из MsgBox2884Public Const resBad = 0 ' выход, закрытием окна2885Public Const resOk = 1 ' Да2886Public Const resNo = 2 ' Нет2887Public Const resCancel = 3 ' Отмена28882889' константы типов данных2890Public Const ccInteger As Byte = 02891Public Const ccString As Byte = 128922893' флаги доступа доступа к БД2894 ' требовать пароль для входа2895Public Const flPasswordNeed As Byte = 12896 ' запрещать доступ на чтение без пароля2897Public Const flReadOnlyEnable As Byte = 22898 ' зашифрованность данных2899Public Const flCoded As Byte = 429002901' для диаграмм2902Type TDiagElem2903 Text As String2904 Val As Integer2905 Color As Long2906End Type29072908' права Только чтение2909Public Sub ProtectedMsg() 2910 Call MsgForm. ErrorMsg("Недостаточно прав для выполнения действия! ") 2911End Sub29122913' звук нажатия кнопки2914Public Sub SoundClick() 2915 Call sndPlaySound("Data\Click. wav", SND_ASYNC + SND_FILENAME + SND_LOOP + SND_APPLICATION) 2916End Sub29172918Public Function IsInteger(ByVal str$) As Boolean2919 Dim Arr(1 To 4) As String * 12920 Arr(1) = "e": Arr(2) = "E": Arr(3) = ",": Arr(4) = ". "2921 IsInteger = True2922 If IsNumeric(str) Then2923 For i% = LBound(Arr) To UBound(Arr) 2924 If (InStr(1, str, Arr(i)) > 0) Then2925 IsInteger = False2926 Exit For2927 End If2928 Next i2929 Else2930 IsInteger = False2931 End If2932End Function29332934Public Sub ButEnabled(Pict As Image, Lbl As Label, enbl As Boolean) 2935 If enbl Then2936 Pict. Picture = MainForm. ButtonImageList. ListImages(1). Picture2937 Lbl. MousePointer = 12938 Else2939 Pict. Picture = MainForm. ButtonImageList. ListImages(2). Picture2940 Lbl. MousePointer = 122941 End If2942 Lbl. Tag = CInt(enbl) 2943End SubМодуль: QueryRunner. bas2944Public QRDBIndex%29452946'***********************************2947' Запросы чувствительны к регистру! 2948'***********************************29492950' константы видов запросов2951 ' ОБЯЗАТЕЛЬНО 3 ЗНАКА2952Public Const sAdd$ = "Add"2953Public Const sDel$ = "Del"2954Public Const sSort$ = "Srt"2955Public Const sOut$ = "Out"2956Public Const sSwap$ = "Swp"2957Public Const sChange$ = "Chg"29582959' константы подтипов запросов2960Public Const sCol$ = "Col"2961Public Const sRow$ = "Row"2962Public Const sTable$ = "Tbl" ' только для использования в запросе Вывод2963Public Const sAZ$ = "AZ"2964Public Const sZA$ = "ZA"2965Public Const sEqual$ = "? ="2966Public Const sAbove$ = "? >"2967Public Const sBelow$ = "? <"2968Public Const sCountEqual$ = "+="2969Public Const sCountAbove$ = "+>"2970Public Const sCountBelow$ = "+<"2971Public Const sI$ = "i"2972Public Const sS$ = "s"2973Public Const sYes$ = "yes"2974Public Const sNo$ = "no"2975Public Const sType$ = "Type"2976Public Const sName$ = "Name"29772978' остальные константы2979Public Const sSep$ = "; "29802981'************************ Формирует строку добавления 'What' ************************2982Public Function Generate_Add(ByVal what$) As String2983 If (what = sCol) Then2984 s$ = AddColForm. AddColDlg(QRDBIndex) 2985 If (s <> "") Then2986 Generate_Add = sAdd + sCol + "(" + s + ")"2987 Else2988 Generate_Add = ""2989 End If2990 Else2991 Generate_Add = sAdd + sRow + "()"2992 End If2993End Function29942995'************************ Формирует строку удаления 'What' ************************2996Public Function Generate_Del(ByVal what$) As String2997 With SelectForm. CheckConfirm2998. value = 12999. Visible = True3000 End With3001 Dim conf$3002 3003 If (what = sCol) Then3004 s$ = SelectForm. SelectDlg(QRDBIndex, "Выберите удаляемое поле", sCol) 3005 If (s <> - 1) Then3006 If (SelectForm. CheckConfirm. value = 1) Then3007 conf = sYes3008 Else3009 conf = sNo3010 End If3011 Generate_Del = sDel + sCol + "(" + s + ", " + conf + ")"3012 Else3013 Generate_Del = ""3014 End If3015 Else3016 s$ = SelectForm. SelectDlg(QRDBIndex, "Выберите удаляемую запись", sRow) 3017 If (s <> - 1) Then3018 If (SelectForm. CheckConfirm. value = 1) Then3019 conf = sYes3020 Else3021 conf = sNo3022 End If3023 Generate_Del = sDel + sRow + "(" + s + ", " + conf + ")"3024 Else3025 Generate_Del = ""3026 End If3027 End If3028End Function30293030'************************ Формирует строку сортировки по 'What' ************************3031Public Function Generate_Sort(ByVal what$) As String3032 SelectForm. CheckConfirm. Visible = False30333034 s$ = SelectForm. SelectDlg(QRDBIndex, "Выберите поле сортировки", sCol) 3035 If (s <> - 1) Then3036 Generate_Sort = sSort + "(" + s + ", " + what + ")"3037 Else3038 Generate_Sort = ""3039 End If3040End Function30413042'************************ Формирует строку вывода по 'What' ************************3043Public Function Generate_Out(ByVal what$) As String3044 Generate_Out = ""3045 SelectForm. CheckConfirm. Visible = False3046 Dim str$3047 3048 s$ = SelectForm. SelectDlg(QRDBIndex, "Выберите поле", sCol) 3049 If (s <> "-1") Then3050 str = Trim(InputForm. InputVal("Введите относительное значение")) 3051 If (str <> "") Then3052 Dim CreateNewTab As Boolean3053 CreateNewTab = (MsgForm. QuestMsg("Выводить в новую таблицу? Нет для вывода в уже существующую. ") = resOk) 3054 If (Not CreateNewTab) Then3055 Table$ = SelectForm. SelectDlg(QRDBIndex, "Выберите таблицу", sTable) 3056 If (Table = "-1") Then Exit Function3057 Generate_Out = sOut + "(" + s + ", " + what + str + ", " + Table + ")"3058 Else3059 Generate_Out = sOut + "(" + s + ", " + what + str + ")"3060 End If3061 Else3062 Call MsgForm. ErrorMsg("Не задано относительное значение! ") 3063 End If3064 End If3065End Function30663067'************************ Формирует строку обмена по 'What' ************************3068Public Function Generate_Swap(ByVal what$) As String3069 If (what = sCol) Then3070 s$ = SelectForm. MultiSelectDlg(QRDBIndex, "Выберите 2 обмениваемых поля", sCol) 3071 If (s <> "") Then3072 p% = InStr(1, s, ",") 3073 Generate_Swap = sSwap + sCol + "(" + Left(s, p - 1) + ", " + Mid(s, p + 1) + ")"3074 Else3075 Generate_Swap = ""3076 End If3077 Else3078 s$ = SelectForm. MultiSelectDlg(QRDBIndex, "Выберите 2 обмениваемые записи", sRow) 3079 If (s <> "") Then3080 p% = InStr(1, s, ",") 3081 Generate_Swap = sSwap + sRow + "(" + Left(s, p - 1) + ", " + Mid(s, p + 1) + ")"3082 Else3083 Generate_Swap = ""3084 End If3085 End If3086End Function30873088'************************ Формирует строку изменения 'What' ************************3089Public Function Generate_Change(ByVal what$) As String3090 Generate_Change = ""3091 SelectForm. CheckConfirm. Visible = False3092 3093 s$ = SelectForm. SelectDlg(QRDBIndex, "Выберите изменяемое поле", sCol) 3094 If (s = "-1") Then Exit Function3095 Select Case what3096 Case sType ' Изменение типа поля3097 Generate_Change = sChange + sType + "(" + s + ")"3098 Case sName ' Изменение названия столбца3099 Name$ = InputForm. InputVal("Введите новое название поля") 3100 If (Name = "") Then Exit Function3101 Generate_Change = sChange + sName + "(" + s + ", " + Name + ")"3102 End Select3103End Function31043105Sub ErrorInQuery() 3106 Call MsgForm. ErrorMsg("Ошибка в запросе! ") 3107End Sub31083109Function TestZero(i%) 3110 If (i = 0) Then3111 Call ErrorInQuery3112 TestZero = True3113 Else3114 TestZero = False3115 End If3116End Function31173118Sub AddRun(what$, str$) 3119 Select Case what3120 Case sCol3121 ' заголовок3122 p% = InStr(1, str, ",") 3123 If TestZero(p) Then Exit Sub3124 title$ = Trim(Left(str, p - 1)) 3125 str = Mid(str, p + 1) 3126 ' тип3127 p = InStr(1, str, ",") 3128 If TestZero(p) Then Exit Sub3129 ColType$ = Trim(Left(str, p - 1)) 3130 str = Mid(str, p + 1) 31313132 ' начальное значение3133 p = InStr(1, str, ",") 3134 If TestZero(p) Then Exit Sub3135 StValStr$ = Trim(Left(str, p - 1)) 3136 str = Mid(str, p + 1) 3137 3138 ' позиция3139 ColPosStr$ = str3140 If (Not IsNumeric(ColPosStr)) Then3141 Call ErrorInQuery3142 Exit Sub3143 End If3144 ColPos% = CInt(ColPosStr) 3145 3146 If ItColAlreadyCreate(QRDBIndex, title) Then3147 Call MsgForm. ErrorMsg("Добавляемое поле уже существует! ") 3148 Exit Sub3149 End If3150 3151 ' в зависимости от типа определяю значение3152 Select Case ColType3153 Case sI3154 If (Not IsInteger(StValStr)) Then3155 Call ErrorInQuery3156 Exit Sub3157 End If3158 stval = CInt(StValStr) 3159 Call AddCol(QRDBIndex, ccInteger, title, stval, ColPos) 3160 Case sS3161 stval = CStr(StValStr) 3162 Call AddCol(QRDBIndex, ccString, title, stval, ColPos) 3163 Case Default3164 Call ErrorInQuery3165 Exit Sub3166 End Select31673168 Case sRow3169 If (DB(QRDBIndex). Header. ColCount > 0) Then3170 Dim row() As Variant3171 ReDim row(DB(QRDBIndex). Header. ColCount - 1) 3172 For i = 0 To DB(QRDBIndex). Header. ColCount - 13173 row(i) = DB(QRDBIndex). Cols(i). DefValue3174 Next i3175 If (Not FindRow(QRDBIndex, row)) Then3176 Call AddField(QRDBIndex, row) 3177 Else3178 Call MsgForm. ErrorMsg("Добавляемый столбец дублируется! ") 3179 End If3180 Else3181 Call MsgForm. ErrorMsg("Нельзя добавлять записи в БД без полей! ") 3182 End If3183 End Select3184 3185End Sub31863187Sub DelRun(what$, str$) 3188 p% = InStr(1, str, ",") 3189 If TestZero(p) Then Exit Sub3190 IndexStr$ = Trim(Left(str, p - 1)) 3191 If (Not IsInteger(IndexStr)) Then3192 Call ErrorInQuery3193 Exit Sub3194 End If3195 Index% = CInt(IndexStr) 3196 str = Mid(str, p + 1) 3197 ConfirmStr$ = Trim(str) 3198 Dim Confirm As Boolean3199 Select Case ConfirmStr3200 Case sYes3201 Confirm = True3202 Case sNo3203 Confirm = False3204 Case Default3205 Call ErrorInQuery3206 Exit Sub3207 End Select3208 3209 Select Case what3210 Case sCol3211 If (DB(QRDBIndex). Header. ColCount > 0) Then3212 Call DelCol_(QRDBIndex, Index, Confirm) 3213 Else3214 Call MsgForm. ErrorMsg("В БД нет полей! ") 3215 Exit Sub3216 End If3217 Case sRow3218 If (DB(QRDBIndex). Header. RowCount > 0) Then3219 Call DelRow_(QRDBIndex, Index, Confirm) 3220 Else3221 Call MsgForm. ErrorMsg("В БД нет записей! ") 3222 Exit Sub3223 End If3224 End Select3225End Sub32263227Sub SortRun(str$) 3228 If (DB(QRDBIndex). Header. ColCount = 0) Or (DB(QRDBIndex). Header. RowCount = 0) Then3229 Call MsgForm. ErrorMsg("Нечего сортировать! ") 3230 Exit Sub3231 End If3232 3233 p% = InStr(1, str, ",") 3234 If TestZero(p) Then Exit Sub3235 what$ = Trim(Left(str, p - 1)) 3236 3237 If (Not IsInteger(what)) Then3238 Call ErrorInQuery3239 Exit Sub3240 End If3241 3242 whatint% = CInt(what) 3243 3244 If (whatint < 0) Or (whatint > DB(QRDBIndex). Header. ColCount - 1) Then3245 Call ErrorInQuery3246 Exit Sub3247 End If3248 3249 Mode$ = Trim(Mid(str, p + 1)) 3250 3251 Select Case Mode3252 Case sAZ3253 s$ = "А->Я"3254 Case sZA3255 s$ = "Я->А"3256 Case Default3257 Call ErrorInQuery3258 Exit Sub3259 End Select3260 3261 Count% = MainForm. TabStrip. Tabs. Count3262 ReDim Preserve DB(Count) 3263 3264 DB(Count) = DB(QRDBIndex) 3265 3266 MainForm. TabStrip. Tabs. Add pvCaption: =s, pvImage: =13267 3268 Dim find As Boolean, needswap As Boolean3269 Dim tmp As TDBElem3270 With DB(Count) 3271 Do3272 find = False3273 For R% = 1 To. Header. RowCount - 13274 If (Mode = sZA) Then3275 needswap = (. Rows(R). Fields(whatint) >. Rows(R - 1). Fields(whatint)) 3276 Else3277 needswap = (. Rows(R). Fields(whatint) <. Rows(R - 1). Fields(whatint)) 3278 End If3279 If (needswap) Then3280 tmp =. Rows(R) 3281. Rows(R) =. Rows(R - 1) 3282. Rows(R - 1) = tmp3283 find = True3284 End If3285 Next R3286 Loop While (find) 3287 End With3288End Sub32893290Function Equal(ByVal col%, ByVal row%, ByVal cmpstr$) As Long3291 If (DB(QRDBIndex). Cols(col). Class = ccInteger) Then3292 Rval = CLng(DB(QRDBIndex). Rows(row). Fields(col)) 3293 Equal = (Rval - CLng(cmpstr)) 3294 Else3295 Rval = CStr(DB(QRDBIndex). Rows(row). Fields(col)) 3296 If (Rval = cmpstr) Then3297 Equal = 03298 Else3299 If (Rval > cmpstr) Then3300 Equal = 13301 Else3302 Equal = - 13303 End If3304 End If3305 End If3306End Function33073308Function CalcCount(Index%, c%, value$) As Integer3309 Count% = 03310 For i% = 0 To (DB(Index). Header. RowCount - 1) 3311 If (CStr(DB(Index). Rows(i). Fields(c)) = value) Then Count = Count + 13312 Next i3313 CalcCount = Count3314End Function33153316Function EarlierDontFind(Index%, c%, R%, value$) As Boolean3317 For i% = 0 To (R - 1) 3318 If (CStr(DB(Index). Rows(i). Fields(c)) = value) Then3319 EarlierDontFind = False3320 Exit Function3321 End If3322 Next i3323 EarlierDontFind = True3324End Function33253326Public Function FindRow(Index%, row()) 3327 For R% = 0 To DB(Index). Header. RowCount - 13328 Sum% = 03329 For c% = 0 To DB(Index). Header. ColCount - 13330 If (CStr(DB(Index). Rows(R). Fields(c)) = row(c)) Then Sum = Sum + 13331 Next c3332 If (Sum = DB(Index). Header. ColCount) Then3333 FindRow = True3334 Exit Function3335 End If3336 Next R3337 FindRow = False3338End Function33393340Sub OutRun(str$) 3341 If (DB(QRDBIndex). Header. ColCount = 0) Or (DB(QRDBIndex). Header. RowCount = 0) Then3342 Call MsgForm. ErrorMsg("Не с чем сравнивать! ") 3343 Exit Sub3344 End If3345 3346 p% = InStr(1, str, ",") 3347 what$ = Trim(Left(str, p - 1)) 3348 3349 If (Not IsInteger(what)) Then3350 Call ErrorInQuery3351 Exit Sub3352 End If3353 3354 whatint% = CInt(what) 3355 3356 If (whatint < 0) Or (whatint > DB(QRDBIndex). Header. ColCount - 1) Then3357 Call ErrorInQuery3358 Exit Sub3359 End If3360 3361 pi% = p + 13362 Do3363 Mode$ = Trim(Mid(str, pi, 1)) 3364 pi = pi + 13365 Loop While (Mode = "") 3366 Mode = Mode + Mid(str, pi, 1) 3367 3368 If (Mode <> sEqual) And (Mode <> sAbove) And (Mode <> sBelow) And (Mode <> sCountEqual) And (Mode <> sCountAbove) And (Mode <> sCountBelow) Then3369 Call ErrorInQuery3370 Exit Sub3371 End If3372 3373 Dim CalcMode As Boolean3374 CalcMode = (Mode = sCountEqual) Or (Mode = sCountAbove) Or (Mode = sCountBelow) 3375 3376 str = Trim(Mid(str, pi + 1)) 3377 3378 If (str = "") Then3379 Call ErrorInQuery3380 Exit Sub3381 End If3382 3383 ' проверка на наличие индекса таблицы3384 p = InStr(1, str, ",") 3385 tableindex% = - 13386 If (p <> 0) Then3387 tableindexstr$ = Trim(Mid(str, p + 1)) 3388 If Not IsInteger(tableindexstr) Then3389 Call ErrorInQuery3390 Exit Sub3391 End If3392 tableindex% = CLng(tableindexstr) 3393 If (tableindex < 0) Or (tableindex > MainForm. TabStrip. Tabs. Count - 1) Then3394 Call ErrorInQuery3395 Exit Sub3396 End If3397 str = Trim(Left(str, p - 1)) 3398 End If3399 3400 Dim GlobEqual As Boolean3401 If (Not IsInteger(str)) And (DB(QRDBIndex). Cols(whatint). Class = ccInteger) Then3402 Call MsgForm. ErrorMsg("Эквивалентом вывода целочисленного столбца не является целое число! " + vbCrLf + _3403 "Условие всегда истинно! ") 3404 GlobEqual = True3405 Else3406 GlobEqual = False3407 End If3408 3409 Count% = MainForm. TabStrip. Tabs. Count3410 If (tableindex = - 1) Then3411 ReDim Preserve DB(Count) 3412 3413 DB(Count). Header = DB(QRDBIndex). Header3414 DB(Count). Header. RowCount = 03415 DB(Count). Cols = DB(QRDBIndex). Cols3416 3417 MainForm. TabStrip. Tabs. Add pvCaption: ="Вывод " + Mode + str, pvImage: =13418 Else3419 Count = tableindex3420 End If3421 3422 Dim NeedAdd As Boolean3423 With DB(Count) 3424 Dim Rval3425 For R% = 0 To DB(QRDBIndex). Header. RowCount - 13426 If (Not GlobEqual) Then3427 Select Case Mode3428 Case sEqual3429 NeedAdd = (Equal(whatint, R, str) = 0) 3430 Case sAbove3431 NeedAdd = (Equal(whatint, R, str) > 0) 3432 Case sBelow3433 NeedAdd = (Equal(whatint, R, str) < 0) 3434 Case sCountEqual3435 value$ = CStr(DB(QRDBIndex). Rows(R). Fields(whatint)) 3436 NeedAdd = ((CStr(CalcCount(QRDBIndex, whatint, value)) = str) And (EarlierDontFind(QRDBIndex, whatint, R, value))) 3437 Case sCountAbove3438 value$ = CStr(DB(QRDBIndex). Rows(R). Fields(whatint)) 3439 NeedAdd = ((CStr(CalcCount(QRDBIndex, whatint, value)) > str) And (EarlierDontFind(QRDBIndex, whatint, R, value))) 3440 Case sCountBelow3441 value$ = CStr(DB(QRDBIndex). Rows(R). Fields(whatint)) 3442 NeedAdd = ((CStr(CalcCount(QRDBIndex, whatint, value)) < str) And (EarlierDontFind(QRDBIndex, whatint, R, value))) 3443 End Select3444 Else3445 NeedAdd = True3446 End If3447 If (NeedAdd) Then3448 ReDim tmparr(DB(QRDBIndex). Header. ColCount) 3449 tmparr = DB(QRDBIndex). Rows(R). Fields3450 If (Not FindRow(Count, tmparr)) Then3451 addindex% = DB(Count). Header. RowCount3452 ReDim Preserve DB(Count). Rows(addindex) 3453 ReDim DB(Count). Rows(addindex). Fields(DB(Count). Header. ColCount - 1) 3454 DB(Count). Rows(addindex). Fields = DB(QRDBIndex). Rows(R). Fields3455 DB(Count). Header. RowCount = DB(Count). Header. RowCount + 13456 Else3457 Call MsgForm. ErrorMsg("Добавляемая запись уже существует! ") 3458 End If3459 End If3460 Next R3461 End With3462End Sub34633464Sub SwapRun(what$, str$) 3465 p% = InStr(1, str, ",") 3466 If TestZero(p) Then Exit Sub3467 index1str$ = Trim(Left(str, p - 1)) 3468 index2str$ = Trim(Mid(str, p + 1)) 3469 3470 If (Not IsInteger(index1str)) Then3471 Call ErrorInQuery3472 Exit Sub3473 End If3474 3475 index1% = CInt(index1str) 3476 index2% = CInt(index2str) 3477 3478 If (index1 < 0) Or (index2 < 0) Or (index1 = index2) Then3479 Call ErrorInQuery3480 Exit Sub3481 End If3482 3483 Select Case what3484 Case sCol3485 With DB(QRDBIndex) 3486 If (index1 >. Header. ColCount - 1) Or (index2 >. Header. ColCount - 1) Then3487 Call ErrorInQuery3488 Exit Sub3489 End If3490 ' обмен полей3491 Dim tmpcol As TDBElemData3492 tmpcol =. Cols(index1) 3493. Cols(index1) =. Cols(index2) 3494. Cols(index2) = tmpcol3495 ' обмен полей записей3496 Dim tmpcell As Variant3497 For R% = 0 To. Header. RowCount - 13498 tmpcell =. Rows(R). Fields(index1) 3499. Rows(R). Fields(index1) =. Rows(R). Fields(index2) 3500. Rows(R). Fields(index2) = tmpcell3501 Next R3502 3503 End With3504 Case sRow3505 With DB(QRDBIndex) 3506 If (index1 >. Header. RowCount - 1) Or (index2 >. Header. RowCount - 1) Then3507 Call ErrorInQuery3508 Exit Sub3509 End If3510 Dim tmprow As TDBElem3511 tmprow =. Rows(index1) 3512. Rows(index1) =. Rows(index2) 3513. Rows(index2) = tmprow3514 End With3515 End Select3516End Sub35173518Sub ChangeRun(what$, param$) 3519 Select Case what3520 Case sType ' **************...::: Type:::... ***************3521 If Not IsInteger(param) Then3522 Call ErrorInQuery3523 Exit Sub3524 End If3525 colindex% = CLng(param) 3526 If (colindex < 0) Or (colindex > DB(QRDBIndex). Header. ColCount - 1) Then3527 Call ErrorInQuery3528 Exit Sub3529 End If3530 If (DB(QRDBIndex). Cols(colindex). Class = ccString) Then3531 If (MsgForm. QuestMsg("Поле строкового типа преобразуется в числовой тип. " + _3532 "Все нечисловые значения будут преобразованы в 0. " + _3533 "Продолжить? ") <> resOk) Then Exit Sub3534 3535 End If3536 For i% = 0 To (DB(QRDBIndex). Header. RowCount - 1) 3537 Select Case DB(QRDBIndex). Cols(colindex). Class3538 Case ccInteger3539 DB(QRDBIndex). Rows(i). Fields(colindex) = CStr(DB(QRDBIndex). Rows(i). Fields(colindex)) 3540 Case ccString3541 If Not IsInteger(DB(QRDBIndex). Rows(i). Fields(colindex)) Then3542 DB(QRDBIndex). Rows(i). Fields(colindex) = 03543 Else3544 DB(QRDBIndex). Rows(i). Fields(colindex) = CLng(DB(QRDBIndex). Rows(i). Fields(colindex)) 3545 End If3546 End Select3547 Next i3548 Select Case DB(QRDBIndex). Cols(colindex). Class3549 Case ccInteger3550 DB(QRDBIndex). Cols(colindex). Class = ccString3551 Case ccString3552 DB(QRDBIndex). Cols(colindex). Class = ccInteger3553 End Select3554 3555 Case sName ' **************...::: Name:::... ***************3556 p% = InStr(1, param, ",") 3557 If TestZero(p) Then Exit Sub3558 colindexstr$ = Trim(Left(param, p - 1)) 3559 If Not IsInteger(colindexstr) Then3560 Call ErrorInQuery3561 Exit Sub3562 End If3563 colindex% = CLng(colindexstr) 3564 param = Trim(Mid(param, p + 1)) 3565 If (param = "") Then3566 Call ErrorInQuery3567 Exit Sub3568 End If3569 ' поиск на дубликат3570 For i% = 0 To DB(QRDBIndex). Header. ColCount - 13571 If (DB(QRDBIndex). Cols(i). title = param) And (i <> colindex) Then3572 Call MsgForm. ErrorMsg("Поле с названием " + param + " уже существует! ") 3573 Exit Sub3574 End If3575 Next i3576 DB(QRDBIndex). Cols(colindex). title = param3577 DB(QRDBIndex). Cols(colindex). TitleLen = Len(param) 3578 Case Default ' **************!! ***************3579 Call ErrorInQuery3580 End Select3581End Sub35823583Public Sub RunQuery(DBIndex_%, query$) 3584 Dim s1$, p%35853586 s1 = Mid(query, 4) 3587 query = Left(query, 3) 3588 3589 QRDBIndex = DBIndex_3590 3591 Select Case query3592 Case sAdd3593 query = Left(s1, 3) 3594 s1 = Mid(s1, InStr(1, s1, "(")) 3595 If (Left(s1, 1) <> "(") Or (Right(s1, 1) <> ")") Or ((Len(s1) < 8) And (query = sCol)) Then3596 Call ErrorInQuery3597 Else3598 Call AddRun(query, Trim(Mid(s1, 2, Len(s1) - 2))) 3599 End If3600 Case sDel3601 query = Left(s1, 3) 3602 s1 = Mid(s1, InStr(1, s1, "(")) 3603 If (Left(s1, 1) <> "(") Or (Right(s1, 1) <> ")") Or (Len(s1) < 5) Then3604 Call ErrorInQuery3605 Else3606 Call DelRun(query, Trim(Mid(s1, 2, Len(s1) - 2))) 3607 End If3608 Case sSort3609 If (Left(s1, 1) <> "(") Or (Right(s1, 1) <> ")") Or (Len(s1) < 5) Then3610 Call ErrorInQuery3611 Else3612 Call SortRun(Trim(Mid(s1, 2, Len(s1) - 2))) 3613 End If3614 Case sOut3615 If (Left(s1, 1) <> "(") Or (Right(s1, 1) <> ")") Or (Len(s1) < 5) Then3616 Call ErrorInQuery3617 Else3618 Call OutRun(Trim(Mid(s1, 2, Len(s1) - 2))) 3619 End If3620 Case sSwap3621 query = Left(s1, 3) 3622 s1 = Mid(s1, InStr(1, s1, "(")) 3623 If (Left(s1, 1) <> "(") Or (Right(s1, 1) <> ")") Or ((Len(s1) < 5) And (query = sCol)) Then3624 Call ErrorInQuery3625 Else3626 Call SwapRun(query, Trim(Mid(s1, 2, Len(s1) - 2))) 3627 End If3628 Case sChange3629 query = Left(s1, 4) 3630 s1 = Mid(s1, InStr(1, s1, "(")) 3631 If (Left(s1, 1) <> "(") Or (Right(s1, 1) <> ")") Or (Len(s1) < 3) Then3632 Call ErrorInQuery3633 Else3634 Call ChangeRun(query, Trim(Mid(s1, 2, Len(s1) - 2))) 3635 End If3636 End Select3637 3638End Sub
Страницы: 1, 2, 3, 4
|
|