我们有时在需要直接使用比较复杂的sql语句往往会碰到好多参数要传入,往往会忙得不亦乐乎,今天和大家分享下比较好的格式化方法。
String.java中提供了一个方法:
/**
* Returns a formatted string using the specified format string and
* arguments.
*
*
The locale always used is the one returned by {@link
* java.util.Locale#getDefault() Locale.getDefault()}.
*
* @param format
* A format string
*
* @param args
* Arguments referenced by the format specifiers in the format
* string. If there are more arguments than format specifiers, the
* extra arguments are ignored. The number of arguments is
* variable and may be zero. The maximum number of arguments is
* limited by the maximum dimension of a Java array as defined by
* the Java
* Virtual Machine Specification. The behaviour on a
* null argument depends on the
* href="../util/Formatter.html#syntax">conversion.
*
* @throws IllegalFormatException
* If a format string contains an illegal syntax, a format
* specifier that is incompatible with the given arguments,
* insufficient arguments given the format string, or other
* illegal conditions. For specification of all possible
* formatting errors, see the
* href="../util/Formatter.html#detail">Details section of the
* formatter class specification.
*
* @throws NullPointerException
* If the format is null
*
* @return A formatted string
*
* @see java.util.Formatter
* @since 1.5
*/
public static String format(String format, Object ... args) {
return new Formatter().format(format, args).toString();
}
我们在使用的时候只需要这样:
String sql =String.format("select * from s%","TB_student");