我有一个Delphi2010应用程序使用ADO来支持一个数据库,可以是SQL Server或MS Access。使用参数化查询将SQL发送到数据库时,可以正确处理日期表示形式的差异。但我偶尔也需要形成动态SQL并将其发送到数据库。
有没有办法让TADOConnection将我的日期格式化为适合当前数据库的文本字符串,或者询问连接以了解应该如何格式化日期?否则,我只能构建一个包含提供者名称和日期格式化函数的表。
发布于 2011-01-14 15:15:20
您还应该能够将参数与动态sql一起使用。我已经在我自己的OPF框架的几个版本中做到了这一点。
只需使用参数编写一条SQL语句,将其作为字符串分配给TAdoQuery (或TAdoCommand)的SQL文本。然后,该组件应该解析您的文本并为您设置参数集合。之后,您应该能够为您的参数赋值,并调用Open或Execute...
给你一个概念:
DS := DatasetClass.Create( self.Connection );
try
DS.QueryText := SQL.Text;
FillSelectParams( DS );
DS.Open;
try
...
finally
DS.Close;
end;
finally
DS.Free;
end;其中FillSelectParams调用以下FillParams过程:
procedure TSQLDataManager.FillParams(ADS: TCustomDataset);
var
i: integer;
ParamName: string;
Attr: TCustomDomainAttribute;
Ref: TCustomDomainObject;
Value: Variant;
begin
for i := 0 to ADS.ParamCount - 1 do begin
Value := Null;
ParamName := ADS.ParamName[i];
if ParamName = 'Id' then begin
ParamName := 'Identity';
end;
Attr := CDO.AttrByName[ParamName];
if Attr <> nil then begin
Value := ADS.AdjustParamValue( Attr );
end else begin
Ref := CDO.ReferenceByName[ParamName];
if ( Ref <> nil ) and ( Ref.Identity <> C_UnassignedIdentity ) then begin
Value := Ref.Identity;
end;
end;
if Value <> Null then begin
ADS.ParamValue[i] := Value;
end;
end;
end;在本例中,param值取自自定义域对象(CDO),但您可以在这里使用您自己的风格。
AdjustParamValue函数负责几个转换。它已经在TCustomDataSet类子类的ADO版本中实现,以处理不同TDataSet子类的组件变化,但SQL数据库类型没有发挥作用:
function TADODCDataset.AdjustParamValue(Attr: TCustomDomainAttribute): Variant;
begin
if Attr is TIdentityAttribute then begin
if Attr.AsInteger = 0 then begin
Result := Null;
end else begin
Result := Attr.Value;
end;
end else if Attr is TBooleanAttribute then begin
if Attr.AsBoolean then begin
Result := Integer( -1 );
end else begin
Result := Integer( 0 );
end;
end else if Attr is TDateTimeAttribute then begin
if Attr.AsDateTime = 0 then begin
Result := Null;
end else begin
Result := Attr.Value;
end;
end else if Attr is TEnumAttribute then begin
Result := Attr.AsString
end else begin
Result := Attr.Value;
end;
end;发布于 2011-01-14 05:31:09
Larry,我会给你一个关于SQL Server部分的答案。
您可以使用sys.syslanguages系统视图来获取有关安装在sql server中的语言的信息,该视图返回的一列名为dateformat,它指示日期顺序,例如,DMY。
也使用@@langid (它返回当前正在使用的语言的本地语言标识符(ID)。)函数,您可以编写类似下面这样的代码来获取Sql Server使用的当前日期格式。
select dateformat from sys.syslanguages where langid=@@langid所以现在你有了一个字符串,你可以在delphi中解析它来格式化你的日期。
另一种选择是选择SQL Server的一种预定义格式,并在SQL语句中使用CONVERT函数将字符串转换为日期。
检查此示例,它使用ISO格式进行转换
//The ISO format is yyyymmdd so i can use the FormatDateTime function to convert any TdateTime to a Iso format sdatetiem string
DateStr:=FormatDateTime('YYYYMMDD',Now);
//Now construct the sql server sentence
SqlSentence:=Format('UPDATE MyTable SET DateField=CONVERT(DATETIME,%s,112)',QuotedStr(DateStr));发布于 2011-01-14 15:43:21
尝试使用ODBC日期转义序列,SQL Server和Access OLEDB提供程序可能支持该序列。例如:
{d '2011-01-14'}https://stackoverflow.com/questions/4684987
复制相似问题