1. 程式人生 > >巧用java.text.MessageFormat將JDBC的sql語句引數化

巧用java.text.MessageFormat將JDBC的sql語句引數化

需求:

select id,name from table where id=xxx and name=xxx;
其中, 需要將id,name引數化

解決方案:

方案一: String.format

String.format("select %s,%s from table where %s=xxx and %s=xxx;" id, name,  id, name)

方案二: MessageFormat.format

import java.text.MessageFormat; 
MessageFormat.format("select {0},{1} from table where {0}=xxx and {1}=xxx"
, id, name)

高階應用

輸出資料庫表的每一行的指定的幾列

String sql = MessageFormat.format(
    "select {0},{1} from {2} where {0}='{3}' and {1}='{4}';",
    "id", "name", "t_student",
    "1213", "gaga"
    )
// select id,name from t_student where id='1213' and name ='gaga';
con = connection;
st = con.createStatement();
rs = st.executeQuery(sql);
ResultSetMetaData rsMeta = rs.getMetaData();
int
columnCount = rsMeta.getColumnCount(); List<String[]> resultList = new LinkedList<>(); while (rs.next()) { String[] resultRow = new String[columnCount]; // column id start from left, and start from 1 for (int i = 1; i <= columnCount; i++) { String element = rs.getString(i); resultRow[i - 1
] = element == null ? "" : element; } resultList.add(resultRow); }