我一直在用桌子敲打桌子。我有一个包含2列的简单表,如下所示:
CREATE TABLE [dbo].[MiscInitializers](
[PKey] [int] IDENTITY(1,1) NOT NULL,
[Value] [text] NULL,
CONSTRAINT [PK_MiscInitializers] PRIMARY KEY CLUSTERED
(
[PKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
我正在尝试使用如下过程更新行:
function TdmSQL.SetInitializer(Value: string; var Key: string): boolean;
const
UpdateCmd =
'update MiscInitializers set Value = :theValue where PKey = :theKey';
InsertCmd = 'insert into MiscInitializers (Value) values (:Param1)';
var
tmp: integer;
rsTmp: TADODataSet;
foo: TParameter;
sTmp: string;
begin
Result := false;
adoGenericCommand.CommandText := '';
adoGenericCommand.Parameters.Clear;
if Key <> '' then
begin
// attempt update
if not TryStrToInt(Key, tmp) then
exit;
adoGenericCommand.CommandText := UpdateCmd;
adoGenericCommand.Prepared := true;
adoGenericCommand.Parameters.Refresh;
// some debug stuff
sTmp := Format('Num Params: %d', [adoGenericCommand.Parameters.Count]);
ShowMessageBox(sTmp);
for tmp := 0 to adoGenericCommand.Parameters.Count - 1 do
begin
sTmp := Format('Param %d: Name %s',
[tmp, adoGenericCommand.Parameters.Items[tmp].Name]);
ShowMessageBox(sTmp);
end;
// end debug stuff
foo := adoGenericCommand.Parameters.ParamByName('theValue');
foo.Value.AsString := Value;
foo := adoGenericCommand.Parameters.ParamByName('theKey');
foo.Value := Key;
rsTmp.Recordset := adoGenericCommand.Execute;
Result := rsTmp.RecordCount = 1;
exit;
// etc
我看到的(使用那些调试消息框调用)是update命令获取2个参数,但它们的名称是Param1和Param2,而不是theValue和theKey。
有没有办法在运行时设置参数,所以ParamByName调用将使用我真正想要的名称,而不是我得到的Param * N *?
答案 0 :(得分:2)
您可以使用ParseSQL生成参数
const
UpdateCmd = 'update MiscInitializers set Value = :theValue where PKey = :theKey';
var
ds: TADODataSet;
I: Integer;
begin
ds := TADODataSet.Create(nil);
try
ds.CommandText := UpdateCmd;
ds.Parameters.ParseSQL(ds.CommandText, True);
for I := 0 to ds.Parameters.Count - 1 do
ShowMessage(ds.Parameters.Items[I].name);
finally
ds.Free;
end;
end;
答案 1 :(得分:0)
分配'CommandText'后,不要在'参数'上调用Refresh
。当您调用'Refresh'时,VCL会转向提供程序以获取参数信息,如果返回的信息不包含参数名称,则VCL会动态地组成它们。