我们有时在需要直接使用比较复杂的sql语句往往会碰到好多参数要传入,往往会忙得不亦乐乎,今天和大家分享下比较好的格式化方法。

String.java中提供了一个方法:

 

 
  
  1. /** 
  2.      * Returns a formatted string using the specified format string and 
  3.      * arguments. 
  4.      * 
  5.      * <p> The locale always used is the one returned by {@link 
  6.      * java.util.Locale#getDefault() Locale.getDefault()}. 
  7.      * 
  8.      * @param  format 
  9.      *         A <a href="../util/Formatter.html#syntax">format string</a> 
  10.      * 
  11.      * @param  args 
  12.      *         Arguments referenced by the format specifiers in the format 
  13.      *         string.  If there are more arguments than format specifiers, the 
  14.      *         extra arguments are ignored.  The number of arguments is 
  15.      *         variable and may be zero.  The maximum number of arguments is 
  16.      *         limited by the maximum dimension of a Java array as defined by 
  17.      *         the <a href="http://java.sun.com/docs/books/vmspec/">Java 
  18.      *         Virtual Machine Specification</a>.  The behaviour on a 
  19.      *         <tt>null</tt> argument depends on the <a 
  20.      *         href="../util/Formatter.html#syntax">conversion</a>. 
  21.      * 
  22.      * @throws  IllegalFormatException 
  23.      *          If a format string contains an illegal syntax, a format 
  24.      *          specifier that is incompatible with the given arguments, 
  25.      *          insufficient arguments given the format string, or other 
  26.      *          illegal conditions.  For specification of all possible 
  27.      *          formatting errors, see the <a 
  28.      *          href="../util/Formatter.html#detail">Details</a> section of the 
  29.      *          formatter class specification. 
  30.      * 
  31.      * @throws  NullPointerException 
  32.      *          If the <tt>format</tt> is <tt>null</tt> 
  33.      * 
  34.      * @return  A formatted string 
  35.      * 
  36.      * @see  java.util.Formatter 
  37.      * @since  1.5 
  38.      */ 
  39.     public static String format(String format, Object ... args) { 
  40.         return new Formatter().format(format, args).toString(); 
  41.     } 

我们在使用的时候只需要这样:

 

 
  
  1. String sql =String.format("select * from s%","TB_student");