I'm executing an UPDATE
statement in a TADOQuery
and I'm using parameters for a few things. Initially, this was working just fine, but I added another parameter for the table name and field name, and now it's breaking.
我正在TADOQuery中执行UPDATE语句,我正在使用参数进行一些操作。最初,这工作正常,但我为表名和字段名添加了另一个参数,现在它正在破坏。
The code looks like this:
代码如下所示:
Q.SQL.Text:= 'update :tablename set :fieldname = :newid where :fieldname = :oldid';
Q.Parameters.ParamValues['tablename']:= TableName;
Q.Parameters.ParamValues['fieldname']:= FieldName;
Q.Parameters.ParamValues['oldid']:= OldID;
Q.Parameters.ParamValues['newid']:= NewID;
And the error I get:
我得到的错误:
I'm assuming this is because I'm using this field name twice. I can overcome this by using another unique field name for the second time it's used, however I still have another error:
我假设这是因为我使用这个字段名称两次。我可以通过第二次使用另一个唯一的字段名称来解决这个问题,但是我还有另一个错误:
How do I use the parameters to specify the table and field to update?
如何使用参数指定要更新的表和字段?
1 个解决方案
#1
5
Query parameters aren't designed to parameterize table names.
查询参数不是为了参数化表名而设计的。
What you can do is use placeholders for the table name(s) in your SQL, and then use the Format
function to replace those with the table name(s), and then use parameters for the other values as usual. This is still relatively safe from SQL injection (the malevolent person would have to know the precise table names, the specific SQL statement being used, and values to provide for parameters).
您可以做的是在SQL中使用占位符作为表名,然后使用Format函数替换具有表名的那些,然后像往常一样使用其他值的参数。这仍然是SQL注入相对安全的(恶意的人必须知道精确的表名,正在使用的特定SQL语句和提供参数的值)。
const
QryText = 'update %s set :fieldname = :newid where :fieldname = :oldid';
begin
Q.SQL.Text := Format(QryText, [TableName]);
Q.Parameters.ParamValues['fieldname'] := FieldName;
Q.Parameters.ParamValues['oldid'] := OldID;
Q.Parameters.ParamValues['newid'] := NewID;
...
end;
#1
5
Query parameters aren't designed to parameterize table names.
查询参数不是为了参数化表名而设计的。
What you can do is use placeholders for the table name(s) in your SQL, and then use the Format
function to replace those with the table name(s), and then use parameters for the other values as usual. This is still relatively safe from SQL injection (the malevolent person would have to know the precise table names, the specific SQL statement being used, and values to provide for parameters).
您可以做的是在SQL中使用占位符作为表名,然后使用Format函数替换具有表名的那些,然后像往常一样使用其他值的参数。这仍然是SQL注入相对安全的(恶意的人必须知道精确的表名,正在使用的特定SQL语句和提供参数的值)。
const
QryText = 'update %s set :fieldname = :newid where :fieldname = :oldid';
begin
Q.SQL.Text := Format(QryText, [TableName]);
Q.Parameters.ParamValues['fieldname'] := FieldName;
Q.Parameters.ParamValues['oldid'] := OldID;
Q.Parameters.ParamValues['newid'] := NewID;
...
end;