如何在Java中创建动态预处理语句? [英] How to create a dynamic prepared statement in Java?

查看:195
本文介绍了如何在Java中创建动态预处理语句?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用预准备语句有助于避免sql注入。我的问题是,准备好的声明通常是非常静态的。我有一个问题,我在运行时根据用户输入构建sql-query的where子句。根据填充的输入字段,我必须将相应的语句添加到where子句中。如何通过预处理语句实现这一点?

I know using prepared statements helps to avoid sql-injection. My problem is, that a prepared statement is usually very static. I have a problem, where I build the where-clause of the sql-query at runtime, depending on user-input. Depending on which input-fields are filled I have to add the correspending statements to the where-clause. How can this be realized with prepared statements?

推荐答案

我想你可以根据他们想要的列动态构建准备好的语句查询,即使用StringBuffer和循环来根据所需的列构建它们。

I guess you could dynamically build your prepared statements based on what columns they want to query, i.e. use a StringBuffer and a loop to build them based on the required columns.

为了提高效率,你应该将它们保存在某种内存中查找中。因此,您最终得到一个Map或其他预准备语句集合,其中检索键是他们设计用于查询的列。

For efficiency you should keep these in some kind of in-memory lookup. So you'd end up with a Map or other collection of prepared statements where the retrieval key is the columns they're designed to query against.

这篇关于如何在Java中创建动态预处理语句?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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