我需要组建一个SQL字符串来搜索数据。给定一系列变量(A,B,C ...),如何形成Sql String Ex“A =?和B =?....”但只考虑非空变量?
我有一个很长的变量,如列表:String id, String fName, String city, int custType, ....
和我的数据库表拥有所有这些列(ID,FName参数,LName的,市...)
我想基于该信息来搜索数据来自提供的变量,但只有非空变量应该用在SQL字符串中。
练习1如果变量是这样的:
String id="22";
String fName="";
String LName="Tom";
String city="";
int custType=0;
然后
String sql="Select * from Customer ";
String where=" where id=? and LName=?";
sql+=where;
//then call DB
练习2如果变量是这样的:
String id="";
String fName="";
String LName="Tom";
String city="Ny";
String postcode="211";
然后
String where=" where LName=? and city=? and postcode=?";
如果只有1个变量是不是空&其他都是空的,则没有必要AND
,前String where=" where LName=?"
我想到把所有可变因素进入名单,但一些可变因素是int型的。我也不知道形成这样的字符串的最佳逻辑是什么。
你能想出任何好的解决方案吗?
但我们必须遍历所有变量?如何 – Tum
你有变量(可能作为参数),检查每一个。为什么需要循环 –