接手修改舊案難免要自己組SQL較快,也不用額外寫POJO,所用一支java main來組Java呼叫JDBC的statement用的SQL字串也較省工些。
假設所有欄位名稱存在List<String>
資料型態的list變數下,可以做成以下SQL的Statement
List<String> list = new ArrayList<String>();
list.add("user_id");
list.add("password");
list.add("username");
System.out.println(list.toString().replaceAll("[\\[\\]]", ""));
System.out.println(list.toString().replaceAll("[^,]+", " ?"));
System.out.println(list.toString().replaceAll("[\\[\\]]", "").replaceAll("[^,]+", "$0 = ?"));
System.out.println(list.toString().replaceAll("[\\[\\]]", "").replaceAll("[^,]+", "$0 = ?").replaceAll(",", " and"));
會得到以下結果:
user_id, password, username # insert into table (欄位清單)
?, ?, ? # insert into table (...) values (問號清單)
user_id = ?, password = ?, username = ? # update table set (欄位鍵值對)
user_id = ? and password = ? and username = ? # select where (條件式)