【发布时间】:2009-08-21 13:40:03
【问题描述】:
这是一个执行以下操作的函数:
- 创建一个长度为 8 的随机 Token
- 将该令牌插入数据库
如果用户已有令牌,请更新它。
如果用户没有令牌,则插入它。
procedure createToken(BenuNr: integer);
var
AQ_Query: TADOQuery;
strToken: string;
intZaehler: integer;
const cCharSet: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
begin
//Random String as Token
SetLength(strToken, 8);
for intZaehler := 1 to 8 do
begin
strToken[intZaehler] := cCharSet[1+Random(Length(cCharSet))];
end;
//Inserts the Token into the Database
with AQ_Query do
begin
try
AQ_Query := TADOQuery.Create(nil);
ConnectionString := strConnectionString;
SQL.Text := 'if EXISTS(select * from TOKN where BENU_NR = :paramBenu_NR) begin update TOKN set TOKEN = :paramTOKEN where BENU_NR = :paramBenu_NR end else insert into TOKN (BENU_NR, TOKEN) values (:paramBENU_NR,:paramTOKEN)';
Prepared := true;
Parameters.ParamByName('paramBENU_NR').DataType := ftInteger;
Parameters.ParamByName('paramTOKEN').DataType := ftString;
Parameters.ParamByName('paramBENU_NR').Value := BenuNr;
Parameters.ParamByName('paramTOKEN').Value := strToken;
ExecSQL; //<< Exception as stated in the title
finally
Free;
end;
end;
end;
执行此操作会引发标题中所述的异常。我把上面的例子删掉了,瞧:没有更多的例外。不幸的是,我不明白为什么?
procedure createToken();
var
AQ_Query: TADOQuery;
strToken: string;
intZaehler: integer;
const cCharSet: string = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
begin
//Random String as Token
SetLength(strToken, 8);
for intZaehler := 1 to 8 do
begin
strToken[intZaehler] := cCharSet[1+Random(Length(cCharSet))];
end;
//Inserts the Token into the Database
with AQ_Query do
begin
try
AQ_Query := TADOQuery.Create(nil);
ConnectionString := strConnectionString;
SQL.Text := 'update TOKN set TOKEN = :paramTOKEN where BENU_NR = 1';
Prepared := true;
Parameters.ParamByName('paramTOKEN').DataType := ftString;
Parameters.ParamByName('paramTOKEN').Value := strToken;
ExecSQL; //<< No more exception
finally
Free;
end;
end;
end;
似乎每个 SQL 只允许 1 个参数。我正在使用 Delphi 7 和 MSSQL Server 2005
知道如何修复第一个代码块以使其正常工作吗?
【问题讨论】:
-
尝试使用sql profiler,分析sql查询。
-
参数名称是否区分大小写?因为您在设置参数时使用了 paramBENU_NR,但在代码中使用了 paramBenu_NR - 如果它们区分大小写,则可能会抱怨,因为您没有在查询中为参数指定值。
标签: delphi parameters ado