假设我有一个包含3列的表格:C1,C2,C3
Let's say I have a table with 3 columns: C1, C2, C3
我根据C1列进行搜索. 我可以做类似这样的事情吗( 这不起作用 -因为这不是 prepareStatement的使用方式:))
I make a search based on the C1 column. Could I make something similar like this (this is not working - because this is not the way prepareStatement it's used:) )
String c;// the name of the column ... String sql = "select * from table where ? = ?"; pre = con.prepareStatement(sql); pre.setString(1, c); pre.setString(1, i); rs = pre.executeQuery();主要思想是,我不想每列都有3个ifs.一个优雅的解决方案?
The main idea, I don't want to have 3 ifs for every column. An elegant solution?
推荐答案您可以编写一组sql查询并将其存储在地图中,然后根据相关列获取一个.
you could code up a a set of sql queries and store them in a map, then grab one based on the column in question.
enum column { a, b, c} Map<column, string> str; static { str.put(a, "select * from tbl where a = ? "); ... }然后根据枚举从地图中抢一张. sql语句中的字符串追加有可能在将来成为安全问题.
then just grab one out of the map later based on the enum. String appends in sql statements have a way of becoming security problems in the future.
更多推荐
PreparedStatement:我可以提供列名作为参数吗?
发布评论