如何使用 ADO 查询参数指定表名和字段名? [英] How to use ADO Query Parameters to specify table and field names?

查看:26
本文介绍了如何使用 ADO 查询参数指定表名和字段名?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个 TADOQuery 中执行一个 UPDATE 语句,并且我正在使用一些参数.最初,这工作得很好,但我为表名和字段名添加了另一个参数,现在它坏了.

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.

代码如下:

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;

我得到的错误:

我假设这是因为我使用了这个字段名称两次.我可以通过第二次使用另一个唯一的字段名称来克服这个问题,但是我仍然有另一个错误:

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?

推荐答案

查询参数不是为了参数化表名而设计的.

Query parameters aren't designed to parameterize table names.

可以做的是在 SQL 中使用表名占位符,然后使用 Format 函数将它们替换为表名),然后像往常一样使用其他值的参数.这对于 SQL 注入还是相对安全的(恶意者必须知道精确的表名、使用的特定 SQL 语句以及提供参数的值).

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).

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;

这篇关于如何使用 ADO 查询参数指定表名和字段名?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆