{****************************************************************************
将aFields字段里面的对应字段保存到ADORs;
ArrField和SFValue,说明需要不需要保存的字段;
(SFValue为true时,保存ArrField里在aFields的字段值到ADORs;
SFValue为False时,保存ArrField里不在aFields的字段值到ADORs;
由于调用fnSetADOFldValue提供的ADORs和Fields结构一样,故调用ADORs.Fields[sFldName].value := aFields[sFldName].Value不会有字段不符的问题
*******************************************************************************
}
function TAdodsOp.fnSetADOFldValue(ADORs:oleVariant;aFields: Fields;ArrField: array of string; SFValue: Boolean): Boolean;
varbIsFind:Boolean;
i,j:Integer;
sFldName:string;
begin
try
for I := 0 to aFields.Count - 1 do //Iterate
begin
bIsFind:=False;
sFldName := aFields[i].Name;
if High(ArrField)>=0 then
begin
for j := 0 to High(ArrField) do
if UpperCase(sFldName)=UpperCase(ArrField[j])then
begin
bIsFind := True;
Break;
end;
if SFValue then //需要赋值
begin
if not bIsFind then Continue;
end
else //不需要
begin
if bIsFind then Continue;
end;
end;
ADORs.Fields[sFldName].value := aFields[sFldName].Value;
end; //for i
Result := True;
except
raise;
Result := False;
end;
end;
//使用原生ADO来保存数据 ,参数TblName可以是表明,也可以是SQL语句
//参数arrfield表示SFValue =true 需要赋值的字段,SFValue=False 表示不需要赋值
//如果是空值表示全部的字段需要赋值
function TForm1.ADoSaveData(ADataSet:TCustomADODataSet;TblName:String;
ArrField: array of string;SFValue:Boolean=True;
RecordType:TAffectRecords=arAll):Boolean;
const
sSQL = 'SELECT * FROM %S WHERE 1=0';
var
ADORs:oleVariant;
FConnObject: _Connection;
vFiltered: Boolean;
vFilterGroup: TFilterGroup;
begin
Result := False;
if ADataSet.IsEmpty then Exit;
if ADataSet.LockType <> ltBatchOptimistic then Exit;
ADORs:=CreateOleObject('ADODB.Recordset');
FConnObject := FGlobalDM.aConnMain.ConnectionObject;
ADORs.Open(Format(sSQL,[TblName]),FConnObject,3,2);
ADataSet.DisableControls;
try
vFiltered := ADataSet.Filtered;
vFilterGroup := ADataSet.FilterGroup;
try
with ADataSet.Recordset do
try
case RecordType of
arAll:
begin
ADataSet.Filtered := True;
ADataSet.FilterGroup := fgPendingRecords;
if not BOF then MoveFirst;
while not eof do
begin
ADORs.Addnew(); //创建一条新记录。
try
fnSetADOFldValue(ADORs,Fields,ArrField,SFValue);
//fnSetADOFldValue(ADORs,ADataSet.Recordset.Fields,ArrField,SFValue);
ADORs.Update;//保存对 Recordset 对象中的一条单一记录所做的更改。
Result := True;
except
raise;
Result := False;
Break;
end;
MoveNext;
end;
end;
arCurrent :
begin
ADORs.AddNew;
try
fnSetADOFldValue(ADORs,Fields,ArrField,SFValue);
ADORs.Update;
Result := True;
except
raise;
Result := False;
end;
end;
end;
If ADORs.State <> adStateClosed Then ADORs.Close;
finally
if not VarIsEmpty(ADORs) then
begin
ADORs := Unassigned;
end;
end;
finally
ADataSet.Filtered := vFiltered;
ADataSet.FilterGroup := vFilterGroup;
end;
finally
ADataSet.EnableControls;
end;
end;