关于三层数据更新的问题。
本帖最后由 xmtrpg 于 2013-06-29 15:44:23 编辑 我用的是MIDAS的三层结构,客户端用Socketconnection连接的。以下有一个服务器端的方法,给客户端调用更新几个表的数据的,麻烦各位大虾看看有什么问题。因为调用那个方法100次总有那么一两次要更新的数据没有更新到,导致数据错误,不知道是什么原因?
function TUDm1.UnJsProc: OleVariant;
var
jscon: TAdoConnection;
AQ1, AQ2: TAdoQuery;
AServer, Auser, APw: string;
ZTName: string;
begin
try
jscon := TAdoConnection.Create(nil);
jscon.LoginPrompt := false;
jscon.ConnectionString := 'Provider=SQLOLEDB.1;Password=' + APw + ';Persist Security Info=True;' +
'User ID=' + Auser + ';Initial Catalog=' + ZTName + ';Data Source=' + Aserver;
try
jscon.Connected := true;
except
on E: Exception do
begin
Result := E.Message;
Exit;
end;
end;
AQ1 := TAdoQuery.Create(nil);
AQ1.Connection := jscon;
AQ1.CursorType := ctStatic;
AQ2 := TAdoQuery.Create(nil);
AQ2.Connection := jscon;
AQ2.CursorType := ctStatic;
jscon.BeginTrans;
with AQ1 do
begin
close;
sql.Clear;
sql.Add('select * from 数据表1 where VpId is not null and workId=''' + workId + '''');
open;
if not IsEmpty then
begin
first;
while not eof do
begin
AQ2.Close;
AQ2.SQL.Clear;
AQ2.SQL.Add('update 数据表2 set RemainCount=RemainCount+' + Fieldbyname('QTY').AsString + ' where VpId=''' + Fieldbyname('VpId').AsString + '''');
try
AQ2.ExecSQL;
except
on E: Exception do
begin
Result := E.Message;
jscon.RollbackTrans;
Exit;
end;
end;
next;
end;
end;
close;
sql.Clear;
sql.Add('select * from 数据表3 where VipXmId is not null and workId=''' + workId + '''');
open;
if not IsEmpty then
begin
first;
while not eof do
begin
AQ2.Close;
AQ2.SQL.Clear;
AQ2.SQL.Add('update 数据表4 set RemainCount=RemainCount+' + Fieldbyname('worktimes').AsString + ' where XmId=''' + Fieldbyname('VipXmId').AsString + '''');
try
AQ2.ExecSQL;
except
on E: Exception do
begin
Result := E.Message;
jscon.RollbackTrans;
Exit;
end;
end;
next;
end;
end;
end;
jscon.CommitTrans;
finally
if AQ1 <> nil then
begin
AQ1.Close;
FreeAndNil(AQ1);
end;
if AQ2 <> nil then
begin
AQ2.Close;
FreeAndNil(AQ2);
end;
if jscon <> nil then
begin
jscon.Close;
FreeAndNil(jscon);
end;
end;
end;
[解决办法]
你的代码是创建新的连接,立即更新数据有问题。因数连接需要时间,如果已经连接上,更新数据无问题。如果没有连接,也就不能更新数据了。建议加一个判断是否连接上的代码,如果OK就更新数据。