Fórum ApplyUpdates naum funciona #294034

01/09/2005

0

Pessoal do forum meu problema é o seguinte:

Tenho um bd access/97 pra ser migrado pra dentro do oracle e estou na fase inicial de um sisteminha simples, só pra migrar os dados, e é a primeira vez q estou tentando usar DBEXPRESS.

O q foi q eu fiz?
fiz o seguinte:
Paleta BDE, peguei um database e uma query.
Paleta DBEXPRESS, peguei um SQLConection e um SimpleDataSet, blz. No meu formulário tem algumas Labels e um gauge. Aí fiz o seguinte procedimento pra recuperar os dados:

procedure TfPrincipal.ObterDados(tabela: string);
begin
//Access - eu tenho q fazer um select * pq eu tenho q migrar todos os dados, eu sei q vai ser muitos registros mais vai ser apenas uma vez.
qrGenerica.Close;
qrGenerica.sql.Text:= ´Select * from ´ + tabela;
qrGenerica.Open;

//Oracle - lembrando aki q a tabela do oracle está vazia, pra ser inserido os dados do access
sdsGenerica.Close;
sdsGenerica.DataSet.CommandText:=´Select * from ´ + tabela;
sdsGenerica.Open;
end;

e outra pra inserção e gravação:

procedure TfPrincipal.IncluirDados(gauge: TGauge);
var x: integer;
campo: string;
begin
try
TotReg := qrGenerica.RecordCount;
RegImp := 0;
gauge.MinValue := 0;
gauge.MaxValue := TotReg;
while not qrGenerica.Eof do
begin
sdsGenerica.Append;
for x:=0 to qrGenerica.Fields.Count-1 do
begin
campo := qrGenerica.Fields[x].FieldName;
sdsGenerica.FieldByName(campo).Value := qrGenerica.FieldByName(campo).Value;
end;
sdsGenerica.Post;
inc(RegImp);
gauge.Progress:=RegImp;
lbTotReg.Caption := IntToStr(TotReg);
lbRegImport.Caption := IntToStr(RegImp);
Application.ProcessMessages;
qrGenerica.Next;
end;
sdsGenerica.ApplyUpdates(0);
except
on e: Exception do MessageDlg(e.Message, mtError, [mbOK], 0);
end;
end;

eu sei q poderia ser tudo uma procedure só, mas eu quis fazer assim.

aí tem um botão q faz o seguinte:

procedure TfPrincipal.btMigrarClick(Sender: TObject);
begin
try
btMigrar.Enabled:=False;

ObterDados(´Estabelecimento´);
lbTabela.Caption := ´ESTABELECIMENTO´;
IncluirDados(gauge);

ShowMessage(´Processo Realizado com Sucesso.´);
btMigrar.Enabled:=True;
except
on e: Exception do MessageDlg(e.Message, mtError, [mbOK], 0);
end;
end;

O programinha funciona legal, aí qnd vou olhar na base, naum tem nada gravado na tabela estabelecimento. Sem falar q essa é a primeira tabela, ainda será migrada outras 20. Fiz com uma primeiro pra testar.

já tentei colocar o applyupdates logo após o post dentro do laço while e mesmo assim naum gravou nada na base, e ainda ficou 50x mais lento.

O q eu estou fazendo de errado? alguem tem alguma dica.


Pabhen

Pabhen

Responder

Posts

01/09/2005

Nandolh

Exiba uma mensagem no evento onReconcileError do ClientDataSet e verifique o erro gerado.


Responder

Gostei + 0

01/09/2005

Pabhen

Exiba uma mensagem no evento onReconcileError do ClientDataSet e verifique o erro gerado.


naum gera nenhum erro. O q mais pode ser?


Responder

Gostei + 0

01/09/2005

Pabhen

[quote:d9fcb4cb93=´nandolh´]Exiba uma mensagem no evento onReconcileError do ClientDataSet e verifique o erro gerado.


naum gera nenhum erro. O q mais pode ser?[/quote:d9fcb4cb93]

foi mal cara, ele gera sim, é q eu nunca usei dbexpress e naum sei como usar diretio esse evento do onReconcileError. Vc poderia me explicar?

eu vi q deu um erro pq rodei dentro do delphi, aí apareceu a seguinte mensagem, ´Não é possivel localizar o registro. Nehuma chave foi especificada.´

Como faço pra resolver isso e como usar direito o evento do reconcile?


Responder

Gostei + 0

01/09/2005

Nandolh

No evento onReconcileError vc consegue ´interceptar´ todas as mensagens de erro que ocorrem durante o uso de um ClientDataSet. Sendo possível realizar os devidos tratamentos.

Para resolver o erro:
´Não é possivel localizar o registro. Nehuma chave foi especificada.´
Vc deve especificar quais campos que fazem parte da sua chave. No componente ClientDataSet abra o ´Fields Editor´ (clicando botao direito ou 2 cliques no componente), selecione o campo que deve fazer parte da chave. Agora procure pela propriedade ´ProviderFlags´ no ´Object Inspector´, lá vc encontrará uma opção chamada de ´pfInKey´, defina true para ela.

É muito importante vc definir uma chave, para que o componente saiba por qual campo ele deve se orientar na hora de fazer um update na tabela ou mesmo uma exclusão.

Leia isto: Achei no help do Delphi 2005

Influencing How Updates Are Applied

The OnUpdateData event gives your dataset provider a chance to indicate how records in the delta packet are applied to the database.

By default, changes in the delta packet are written to the database using automatically generated SQL UPDATE, INSERT, or DELETE statements such as
UPDATE EMPLOYEES
set EMPNO = 748, NAME = ´Smith´, TITLE = ´Programmer 1´, DEPT = 52
WHERE
EMPNO = 748 and NAME = ´Smith´ and TITLE = ´Programmer 1´ and DEPT = 47
Unless you specify otherwise, all fields in the delta packet records are included in the UPDATE clause and in the WHERE clause. However, you may want to exclude some of these fields. One way to do this is to set the UpdateMode property of the provider. UpdateMode can be assigned any of the following values:
UpdateMode values Value Meaning
upWhereAll
All fields are used to locate fields (the WHERE clause).

upWhereChanged
Only key fields and fields that are changed are used to locate records.

upWhereKeyOnly
Only key fields are used to locate records.


You might, however, want even more control. For example, with the previous statement, you might want to prevent the EMPNO field from being modified by leaving it out of the UPDATE clause and leave the TITLE and DEPT fields out of the WHERE clause to avoid update conflicts when other applications have modified the data. To specify the clauses where a specific field appears, use the ProviderFlags property. ProviderFlags is a set that can include any of the values in the following table
ProviderFlags values Value Description
pfInWhere
The field appears in the WHERE clause of generated INSERT, DELETE, and UPDATE statements when UpdateMode is upWhereAll or upWhereChanged.

pfInUpdate
The field appears in the UPDATE clause of generated UPDATE statements.

pfInKey
The field is used in the WHERE clause of generated statements when UpdateMode is upWhereKeyOnly.

pfHidden
The field is included in records to ensure uniqueness, but can´t be seen or used on the client side.


Thus, the following OnUpdateData event handler allows the TITLE field to be updated and uses the EMPNO and DEPT fields to locate the desired record. If an error occurs, and a second attempt is made to locate the record based only on the key, the generated SQL looks for the EMPNO field only:
procedure TMyDataModule1.Provider1UpdateData(Sender: TObject; DataSet: TCustomClientDataSet);
begin
with DataSet do
begin
FieldByName(´TITLE´).ProviderFlags := [pfInUpdate];
FieldByName(´EMPNO´).ProviderFlags := [pfInWhere, pfInKey];
FieldByName(´DEPT´).ProviderFlags := [pfInWhere];
end;
end;
Note: You can use the UpdateFlags property to influence how updates are applied even if you are updating to a dataset and not using dynamically generated SQL. These flags still determine which fields are used to locate records and which fields get updated.


Responder

Gostei + 0

Utilizamos cookies para fornecer uma melhor experiência para nossos usuários, consulte nossa política de privacidade.

Aceitar