简体   繁体   English

MS Access 使用 VBA 和 Form,构建查询字符串并运行它

[英]MS Access using VBA and Form, build a query string and run it

I have a MS Access form where it will ask users to select or type in words that will be used in the where clause for the query.我有一个 MS Access 表单,它将询问用户 select 或输入将在查询的where子句中使用的单词。

When the button is clicked, it will build the string and use that to run the query.单击按钮时,它将构建字符串并使用它来运行查询。 This will be a read only and to view the subset results from a link table in SQL Server.这将是只读的,用于查看 SQL 服务器中链接表的子集结果。 Nothing more.而已。 I tried it with DoCmd.RunSQL but that is only for action type like update, delete, etc.我用DoCmd.RunSQL进行了尝试,但这仅适用于更新、删除等操作类型。

On click button event, it will have similar query.在单击按钮事件上,它将有类似的查询。

strSQL = "Select top 10 * Where ID = ''" + textbox1.value + "'' from linked_Table_Name;"

This did not work.这没有用。

DoCmd.RunSQL strSQL

Firstly, and most importantly, never concatenate user-obtained data as part of a SQL statement .首先,也是最重要的,永远不要将用户获取的数据连接为 SQL 语句的一部分 Any application which uses this technique is wide open to a SQL injection attack and will also fail if the user includes a string delimiter (such as a single quote) or other reserved character in the input they provide.任何使用此技术的应用程序都容易受到SQL 注入攻击,并且如果用户在他们提供的输入中包含字符串分隔符(例如单引号)或其他保留字符,也会失败。

Instead, use parameters.相反,使用参数。

For your scenario, I might suggest creating a saved query with the SQL:对于您的方案,我可能建议使用 SQL 创建一个已保存的查询:

select top 10 t.*
from linked_Table_Name t
where t.ID = Forms![Your Form Name]![textbox1]

Where Your Form Name is the name of your form containing the control textbox1 . Your Form Name是包含控件textbox1的表单的名称。

Then, your on-click event can simply call the OpenQuery method of the DoCmd object:然后,您的点击事件可以简单地调用DoCmd object 的OpenQuery方法:

DoCmd.OpenQuery "YourSavedQuery"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM