Форум программистов
 

Восстановите пароль или Зарегистрируйтесь на форуме, о проблемах и с заказом рекламы пишите сюда - alarforum@yandex.ru, проверяйте папку спам!

Вернуться   Форум программистов > Delphi программирование > БД в Delphi
Регистрация

Восстановить пароль
Повторная активизация e-mail

Купить рекламу на форуме - 42 тыс руб за месяц

Ответ
 
Опции темы Поиск в этой теме
Старый 06.03.2012, 12:17   #1
semak777
 
Регистрация: 25.02.2012
Сообщений: 6
По умолчанию Запись в 3 связные таблицы

Есть 3 таблицы, одна главная, вторая подчиненная первой и третья второй. При записи в них, когда первоначально они пусты и генератор в IBX сброшен на 0 все нормально, но если удалить из главной таблицы одну строчку, то невозможно записать следующие данные, так как в генераторе следующая запись главной таблицы, например, имеет код 3, а в третьей таблице создается генератором код 2 и связь не получается:
Код:
procedure TAddDe.sButton1Click(Sender: TObject);
begin
      try
      with DM.ProductQ do
      begin
      if not DM.IBTransaction1.Active then
      DM.IBTransaction1.StartTransaction;
      //проверяем активность транзакции
      If not DM.ProductQ.Active then
      DM.ProductQ.Open;
      //открываем таблицу
     DM.ProductQ.SQL.Text := 'insert into product (id_product, pname, quantity, price, id_psection, id_punit,id_pgroup, pcomment) values (:id_product, :pname, :quantity, :price, :id_psection, :id_punit, :id_pgroup, :pcomment)';
     DM.ProductQ.ParamByName('pname').AsString := sEdit4.Text;
     DM.ProductQ.ParamByName('quantity').AsInteger := StrToInt(sEdit2.Text);
     DM.ProductQ.ParamByName('price').AsCurrency := StrToCurr(sEdit1.Text);
     DM.ProductQ.ParamByName('id_psection').AsInteger := StrToInt(sDBLookuplistBox3.KeyValue);
     DM.ProductQ.ParamByName('id_punit').AsInteger := StrToInt(sDBLookupListBox2.KeyValue);
     DM.ProductQ.ParamByName('id_pgroup').AsInteger := StrToInt(sDBLookupListBox4.KeyValue);
     DM.ProductQ.ParamByName('pcomment').AsString := sEdit5.Text;
     DM.ProductQ.ExecSQL;
     DM.IBTransaction1.Commit;
     sEdit6.Text := IntToStr(DM.ProductQ.RecordCount + 1); //берем текущее значение для вставки в 3-ю таблицу
     DM.ProductQ.SQL.Text := 'select * from product';
     DM.ProductQ.Open;
     end;

     with DM.DeliveryQ do
      begin
      if not DM.DeliveryT.Active then
      DM.DeliveryT.StartTransaction;
      //проверяем активность транзакции
      If not DM.DeliveryQ.Active then
      DM.DeliveryQ.Open;
      //открываем таблицу
     DM.DeliveryQ.SQL.Text := 'insert into delivery (id_delivery, id_provider, ddate, dsum) values (:id_delivery, :id_provider, :ddate, :dsum)';
     DM.DeliveryQ.ParamByName('id_provider').AsInteger := StrToInt(sDBLookupListBox1.KeyValue);
     DM.DeliveryQ.ParamByName('ddate').AsDate := DateTimePicker1.Date;
     DM.DeliveryQ.ParamByName('dsum').AsCurrency := StrToCurr(sEdit3.Text);
     DM.DeliveryQ.ExecSQL;
     DM.DeliveryT.Commit;
     DM.DeliveryQ.SQL.Text := 'select * from delivery';
     DM.DeliveryQ.Open;
     end;

      with DM.IndeQ do
      begin
      if not DM.IndeT.Active then
      DM.IndeT.StartTransaction;
      //проверяем активность транзакции
      If not DM.IndeQ.Active then
      DM.IndeQ.Open;
      //открываем таблицу
     DM.IndeQ.SQL.Text := 'insert into info_delivery (id_inde, id_delivery, id_product, inde_quantity) values (:id_inde, :id_delivery, :id_product, :inde_quantity)';
     DM.IndeQ.ParamByName('inde_quantity').AsInteger := StrToInt(sEdit2.Text);
     DM.IndeQ.ParamByName('id_product').AsInteger := StrToInt(sEdit6.Text);//вставляем полученное значенние
     DM.IndeQ.ExecSQL;
     DM.IndeT.Commit;
     DM.IndeQ.SQL.Text := 'select * from info_delivery';
     DM.IndeQ.Open;
     end;


     except
      On E: Exception do
      begin
        DM.IBTransaction1.Rollback;
        DM.DeliveryT.Rollback;
        DM.IndeT.Rollback;
        Application.MessageBox(Pchar(E.Message),'Ошибка',MB_ICONERROR);
      end;
      end;
      Close;
end;
Не получается вставить новую запись после удаления из первой таблицы, из-за действий, где выделен комментарий. Как это можно решить? Вставить данные нужно сразу в 3 таблицы.

Последний раз редактировалось semak777; 06.03.2012 в 12:20. Причина: немного ошибся =)
semak777 вне форума Ответить с цитированием
Старый 06.03.2012, 22:21   #2
semak777
 
Регистрация: 25.02.2012
Сообщений: 6
По умолчанию

Проблема решилась )) :
Код:
procedure TAddDe.sButton1Click(Sender: TObject);
  var
    id_product: Integer;
    id_delivery: Integer;
  begin
     with DM.ProductQ do
     begin
     DM.IBTransaction1.Active := false;
     DM.ProductQ.Close;
     DM.ProductQ.SQL.Text := 'insert into product (id_product, pname, quantity, price, id_psection, id_punit,id_pgroup, pcomment) values (:id_product, :pname, :quantity, :price, :id_psection, :id_punit, :id_pgroup, :pcomment)';
     DM.ProductQ.ParamByName('pname').AsString := sEdit4.Text;
     DM.ProductQ.ParamByName('quantity').AsInteger := StrToInt(sEdit2.Text);
     DM.ProductQ.ParamByName('price').AsCurrency := StrToCurr(sEdit1.Text);
     DM.ProductQ.ParamByName('id_psection').AsInteger := StrToInt(sDBLookuplistBox3.KeyValue);
     DM.ProductQ.ParamByName('id_punit').AsInteger := StrToInt(sDBLookupListBox2.KeyValue);
     DM.ProductQ.ParamByName('id_pgroup').AsInteger := StrToInt(sDBLookupListBox4.KeyValue);
     DM.ProductQ.ParamByName('pcomment').AsString := sEdit5.Text;
     DM.IBTransaction1.StartTransaction;
     end;
      try
        DM.ProductQ.ExecSQL;
        DM.IBTransaction1.Commit;
        DM.ProductQ.SQL.Text := 'select * from product';
        DM.ProductQ.Open;
      except
        DM.IBTransaction1.Rollback;
     end;
     DM.ProductQ.Last;
        id_product := DM.ProductQ.FieldByName('id_product').AsInteger;


       with DM.DeliveryQ do
     begin
     DM.DeliveryT.Active := false;
     DM.DeliveryQ.Close;
     DM.DeliveryQ.SQL.Text := 'insert into delivery (id_delivery, id_provider, ddate, dsum) values (:id_delivery, :id_provider, :ddate, :dsum)';
     DM.DeliveryQ.ParamByName('id_provider').AsInteger := StrToInt(sDBLookupListBox1.KeyValue);
     DM.DeliveryQ.ParamByName('ddate').AsDate := DateTimePicker1.Date;
     DM.DeliveryQ.ParamByName('dsum').AsCurrency := StrToCurr(sEdit3.Text);
     DM.DeliveryT.StartTransaction;
     end;
      try
        DM.DeliveryQ.ExecSQL;
        DM.DeliveryT.Commit;
        DM.DeliveryQ.SQL.Text := 'select * from delivery';
        DM.DeliveryQ.Open;
      except
        DM.DeliveryT.Rollback;
     end;
     DM.DeliveryQ.Last;
     id_delivery := DM.DeliveryQ.FieldByName('id_delivery').AsInteger;


        with DM.IndeQ do
     begin
     DM.IndeT.Active := false;
     DM.IndeQ.Close;
     DM.IndeQ.SQL.Text := 'insert into info_delivery (id_inde, id_delivery, id_product, inde_quantity) values (:id_inde, :id_delivery, :id_product, :inde_quantity)';
     DM.IndeQ.ParamByName('id_delivery').AsInteger := id_delivery;
     DM.IndeQ.ParamByName('id_product').AsInteger := id_product;
     DM.IndeQ.ParamByName('inde_quantity').AsInteger := StrToInt(sEdit2.Text);
     DM.IndeT.StartTransaction;
     end;
      try
        DM.IndeQ.ExecSQL;
        DM.IndeT.Commit;
        DM.IndeQ.SQL.Text := 'select * from info_delivery';
        DM.IndeQ.Open;
      except
        DM.IndeT.Rollback;
     end;
  end;
end.
semak777 вне форума Ответить с цитированием
Ответ


Купить рекламу на форуме - 42 тыс руб за месяц

Опции темы Поиск в этой теме
Поиск в этой теме:

Расширенный поиск


Похожие темы
Тема Автор Раздел Ответов Последнее сообщение
Запись из таблицы в файл allegator333 БД в Delphi 1 23.06.2011 02:32
Запись из эдита в ячейку таблицы Balabar Помощь студентам 1 25.11.2010 20:20
Запись таблицы в файл Пони-плакса Помощь студентам 0 24.05.2010 22:52
Связные таблицы в Access Fill_Good_Inc БД в Delphi 0 02.04.2010 20:32
СВЯЗНЫЕ ТАБЛИЦЫ chekanoff БД в Delphi 6 16.09.2009 13:59