巧用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);
}

你可能感兴趣的:(java,printf,字符串格式化,字符串参数化)