我正在使用ADO Command对象来针对SQL Server生成参数化查询。
如果我生成并提供多个参数,则传递所有参数值-第一个参数除外。
如果您想象这样的查询:
SELECT ?, ?, ?, ?, ?
并使用ADO Command对象提供参数值:
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 1);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 2);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 3);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 4);
command.Parameters.Append(command.CreateParameter('', adInteger, adParamInput, 0, 5);
您可以使用Profiler来查看第一个参数值为null:
exec sp_executesql N'SELECT @P1, @P2, @P3, @P4, @P5',N'@P1 int,@P2 int,@P3 int,@P4 int,@P5 int',NULL,2,3,4,5
我用不同的类型,不同的查询,不同的顺序尝试了它。它始终是拒绝提供给数据库服务器的第一个参数。
而且我可以在调用Execute之前确认该参数确实具有值:
command.Parameters[0].Value
我究竟做错了什么?
program Project1;
{$APPTYPE CONSOLE}
{$R *.res}
uses
System.SysUtils,
ActiveX,
ComObj,
ADOint,
Variants;
procedure Main;
var
cs: string;
cn: Connection;
cmd: Command;
p: _Parameter;
recordsAffected: OleVariant;
begin
cs := 'Provider=SQLOLEDB;Data Source=screwdriver;User ID=frog;Password=hunter2';
cn := CoConnection.Create;
WriteLn('Connecting to database...');
cn.Open(cs, '', '', Integer(adConnectUnspecified));
cmd := CoCommand.Create;
cmd.CommandType := adCmdText;
cmd.CommandText := 'IF ? IS NULL RAISERROR(''It was null'', 16, 1);';
cmd.Parameters.Append(cmd.CreateParameter('', adinteger, adParamInput, 0, 1));
cmd.Set_ActiveConnection(cn);
WriteLn('Executing command');
cmd.Execute({out}recordsAffected, Null, adExecuteNoRecords);
end;
begin
try
CoInitialize(nil);
Main;
WriteLn('Success');
except
on E: Exception do
begin
Writeln(E.ClassName, ': ', E.Message);
end;
end;
WriteLn('Press enter to close...');
ReadLn;
end.
您应该在声明中使用EmptyParam
而不是(这是参数)。Null
cmd.Execute
Parameters
cmd.Execute({out}recordsAffected, EmptyParam, adExecuteNoRecords);
请参阅:执行方法(ADO命令)
本EmptyParam
应是一个可选的OLE参数兼容。您也可以OleVariant(cmd).Execute
在示例中使用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句