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

查看:147
本文介绍了如何使用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天全站免登陆