我需要組建一個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
你有變量(可能作爲參數),檢查每一個。爲什麼需要循環 –