2、SQL语句的拼接     

    1. private void button1_Click(object sender, EventArgs e)  
    2.        {  
    3. //先写一个基础的查询语句,即无论是否有条件,都执行这段代码。  
    4. string sql = "select * from T_User";  
    5. //定义一个list<string>类型的集合,用来放拼接的SQL语句  
    6. string> list = new List<string>();  
    7. //根据用户输入的情况来拼接后面的SQL语句。  
    8. if (!string .IsNullOrEmpty(txtID.Text.Trim()))  
    9.            {  
    10. string sqla = "Chr_UserID='" + txtID.Text.Trim() +"'";  
    11.                list.Add(sqla);  
    12.            }  
    13. if (!string .IsNullOrEmpty(txtName.Text .Trim ()))  
    14.            {  
    15. string sqlb = "Chr_Name='" + txtName.Text.Trim() + "'";  
    16.                list.Add(sqlb);  
    17.            }  
    18. if (!string.IsNullOrEmpty(txtClass.Text.Trim()))  
    19.            {  
    20. string sqlb = "Chr_Class='" + txtClass.Text.Trim() + "'";  
    21.                list.Add(sqlb);  
    22.            }  
    23. //判断如果list中有值,即用户输入了某些条件,就开始进行SQL语句的拼接。  
    24. if (list .Count >0)  
    25.            {  
    26. //这个是用了string.join方法,用and作为连接符传来起list中的各个SQL语句  
    27. " where " + string.Join(" and ", list.ToArray());  
    28.            }  
    29.   
    30. string constr = "server=.;database=Charge;uid=sa;pwd=1;";  
    31. new SqlConnection(constr);           
    32.            con.Open();              
    33. new SqlCommand(sql,con);                      
    34.            SqlDataReader dr = sqlcmd.ExecuteReader();  
    35. new DataTable();  
    36. //之后用datatable来接收读取到的数据。  
    37.            dt.Load(dr);  
    38. //赋值给控件。  
    39.            dataGridView1.DataSource = dt;  
    40. //最后记得关闭  
    41.            con.Close();                            
    42.        }  
    43.


    关于java多条件查询SQL语句拼接的小技巧

    最近在实验室做项目的时候遇到了java的多条件查询,翻看了论坛上其他大牛们的博客,都没有给出一个详细的解答。自我探索了一会后给出了下面这样的使用技巧,还算方便,仅供各位参考。

    前端的页面显示:



    java 动态sql模版引擎 java 动态拼接sql_ci

    查询所给的表单代码
    <form action="" >
        <table>
        <tr>
        <td><span>PMNM(内码)</span></td>
        <td><span><input name="PMNM" type="text"></span></td>
        <td><span>PMBM(编码)</span></td>
        <td><span><input name="PMBM" type="text"></span></td>
        <td><span>PMCS(名称)</span></td>
        <td><span><input name="PMCS" type="text"></span></td>
        <td><span>LBQF(类型)</span></td>
        <td><span><input name="LBQF" type="text"></span></td>
        <td><span><input name="codeSubmit" class="search-btn" 
    
    type="submit" value="查询"></span></td>
        </tr>
        </table>
    </form>
    在后台servlet中获取表单的name
    HashMap<String, Object> key=new HashMap<String, Object>();//在不知道属性类型的情况下,用HashMap<String,Object>来代替从上述表单中所获取的name值,并统一存放在HashMap中
                String PMNM=request.getParameter("PMNM");
                key.put("内码", PMNM);
                String PMCS=request.getParameter("PMCS");
                key.put("名称", PMCS);
                String PMBM=request.getParameter("PMBM");
                key.put("编码", PMBM);
                String LBQF=request.getParameter("LBQF");
                key.put("类型",LBQF);
    
        //调用Service层的serach方法进行查询
                ArrayList<Commmon9831> a=h.Search(key);//用ArrayList来表示所查询的结果
                request.setAttribute("a", a);
                request.getRequestDispatcher("所要跳转的显示查询结果页面").forward(request, response);

    DAO层中查询方法了,也是最重要的部分

    public ArrayList<“bean的类型”> Search(HashMap<String ,Object> key )
        {   ArrayList<Commmon9831> a=new ArrayList<Commmon9831>();
           String sql="select * from “数据库名” ";//最原始的sql查询语句
           //依次用Object类来表示HashMap中的属性值
           Object m=key.get("内码");
           Object s=key.get("名称");
           Object P=key.get("编码");
           Object L=key.get("类型");
    
           int count=0;//引入一个count值来控制where条件后的属性值,及在sql语句中的位置
        //注意:**完成上述操作后,并没有判断Object对象是否为空值,下面判断是否为空的方法也很重要**
        if(!(m.toString().equals(""))||!(s.toString().equals(""))||!(P.toString().equals(""))||!(L.toString().equals("")))
           {       sql=sql+" where";
           //如果上述所给条件有一个不为空,则在sql语句中加上“where”。
    
            if(m.toString().equals(""))
               sql=sql+"";
           else{
           //用多个if来表示查询的情况,这里是本文的重点。
           //因为不清楚所给的条件是哪一个,设置count值为0,当在HashMap值前的查询条件不为空,则count++。当count>0时,说明当前查询条件不为一,则sql=sql+“and”。
           if(count>0)
                sql=sql+" and ";
    
                sql=sql+" PMNM = '" +key.get("内码")+ "'";
    
                 if(s.toString().equals(""))
               sql=sql+"";   //sql关键字指尖要存在空格,不然无法执行
           else {if(count>0)
                sql=sql+" and ";
    
                sql=sql+" PMCS = '" +key.get("名称")+ "'";
                count++;
            }
           if(P.toString().equals(""))
               sql=sql+"";
           else {if(count>0)
                sql=sql+" and ";
    
                sql=sql+" PMBM = '" +key.get("编码")+ "'";
                count++;
            }
           if(L.toString().equals(""))
               sql=sql+"";
           else {if(count>0)
                sql=sql+" and ";
    
                sql=sql+" LBQF = '" +key.get("类型")+ "'";
                count++;
            }
           }
           System.out.println(sql);//在控制台上打印出sql语句查看拼接结果
    随笔:

    ———————————————————————————— 

    拼接sql语句是多条件查询的重要部分,在上述所给的技巧中,使用一切查询情况。其中判断HashMap中键值对是否为空,利用count值来判断查询条件情况是本文的重点。



    ===========================================================================


    使用Java注解实现拼接sql语句的功能

    原创  2016年05月14日 16:18:42

    • 1802
    • 0
    • 1

    使用到的两个注解类:

    1. <span style="font-size:18px;">package dao;  
    2.   
    3. import java.lang.annotation.ElementType;  
    4. import java.lang.annotation.Retention;  
    5. import java.lang.annotation.RetentionPolicy;  
    6. import java.lang.annotation.Target;  
    7.   
    8. /**
    9.  * Created by raid on 2016/5/14.
    10.  */  
    11. @Target({ElementType.TYPE})  
    12. @Retention(RetentionPolicy.RUNTIME)  
    13. public @interface Table {  
    14.     String value();  
    15. }  
    16. </span>


      1. package dao;  
      2.   
      3. import java.lang.annotation.ElementType;  
      4. import java.lang.annotation.Retention;  
      5. import java.lang.annotation.RetentionPolicy;  
      6. import java.lang.annotation.Target;  
      7.   
      8. /**
      9.  * Created by raid on 2016/5/14.
      10.  */  
      11. @Target({ElementType.FIELD})  
      12. @Retention(RetentionPolicy.RUNTIME)  
      13. public @interface Column {  
      14.     String value();  
      15. }


      1. package dao;  
      2.   
      3. /**
      4.  * Created by raid on 2016/5/14.
      5.  */  
      6. @Table("user")  
      7. public class Filter {  
      8.   
      9. @Column("id")  
      10. private int id;  
      11.   
      12. @Column("user_name")  
      13. private String userName;  
      14.   
      15. @Column("nick_name")  
      16. private String nickName;  
      17.   
      18. @Column("age")  
      19. private int age;  
      20.   
      21. @Column("city")  
      22. private String city;  
      23.   
      24. @Column("email")  
      25. private String email;  
      26.   
      27. @Column("mobile")  
      28. private String mobile;  
      29.   
      30. public int getId() {  
      31. return id;  
      32.     }  
      33.   
      34. public void setId(int id) {  
      35. this.id = id;  
      36.     }  
      37.   
      38. public String getUserName() {  
      39. return userName;  
      40.     }  
      41.   
      42. public void setUserName(String userName) {  
      43. this.userName = userName;  
      44.     }  
      45.   
      46. public String getNickName() {  
      47. return nickName;  
      48.     }  
      49.   
      50. public void setNickName(String nickName) {  
      51. this.nickName = nickName;  
      52.     }  
      53.   
      54. public int getAge() {  
      55. return age;  
      56.     }  
      57.   
      58. public void setAge(int age) {  
      59. this.age = age;  
      60.     }  
      61.   
      62. public String getCity() {  
      63. return city;  
      64.     }  
      65.   
      66. public void setCity(String city) {  
      67. this.city = city;  
      68.     }  
      69.   
      70. public String getEmail() {  
      71. return email;  
      72.     }  
      73.   
      74. public void setEmail(String email) {  
      75. this.email = email;  
      76.     }  
      77.   
      78. public String getMobile() {  
      79. return mobile;  
      80.     }  
      81.   
      82. public void setMobile(String mobile) {  
      83. this.mobile = mobile;  
      84.     }  
      85. }

      demo类:

      1. package dao;  
      2.   
      3. import java.lang.reflect.Field;  
      4. import java.lang.reflect.Method;  
      5.   
      6. /**
      7.  * Created by raid on 2016/5/14.
      8.  */  
      9. public class Test {  
      10.   
      11. public static void main(String[] args) {  
      12. new Filter();  
      13. 10);//查询ID为10的用户  
      14.   
      15. new Filter();  
      16. "lucy");  
      17.   
      18. new Filter();  
      19. "123@12.com,456@45.com,789@78.com");//查询邮箱为其中任意一个  
      20.   
      21.         String sql1 = query(f1);  
      22.         String sql2 = query(f2);  
      23.         String sql3 = query(f3);  
      24.   
      25.         System.out.println(sql1);;  
      26.         System.out.println(sql2);;  
      27.         System.out.println(sql3);;  
      28.     }  
      29.   
      30. private static String query(Filter f) {  
      31. new StringBuilder();  
      32. //1.获取到class  
      33.         Class c = f.getClass();  
      34. //2.获取到table的名字  
      35. boolean exists = c.isAnnotationPresent(Table.class);  
      36. if (!exists) {  
      37. return null;  
      38.         }  
      39. class);  
      40.   
      41.         String tableName = t.value();  
      42.   
      43. "select * from ").append(tableName).append(" where 1=1");  
      44.   
      45. //2.遍历所有的字段  
      46.         Field[] fArray = c.getDeclaredFields();  
      47. for (Field field : fArray) {  
      48. //4.处理每个字段对应的sql  
      49. //4.1拿到字段名  
      50. boolean fExists = field.isAnnotationPresent(Column.class);  
      51. if (!fExists) {  
      52. continue;  
      53.             }  
      54. class);  
      55.             String columName = column.value();  
      56. //4.2拿到字段值  
      57.             String fieldName = field.getName();  
      58. "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);  
      59. null;  
      60. try {  
      61.                 Method getMethod = c.getMethod(getMethodName);  
      62.                 fieldValue = getMethod.invoke(f);  
      63. catch (Exception e) {  
      64.                 e.printStackTrace();  
      65.             }  
      66. //4.3拼装sql  
      67. if (fieldValue == null || (fieldValue instanceof Integer && (Integer)fieldValue == 0)) {  
      68. continue;  
      69.             }  
      70. if (fieldValue instanceof String) {  
      71. if (((String)fieldValue).contains(",")) {  
      72. ",");  
      73. " in(";  
      74. for (String v : values) {  
      75. "'" + v + "'" + ",";  
      76.                     }  
      77. 0, ((String) fieldValue).length()-1) + ")";  
      78. else {  
      79. "'" + fieldValue + "'";  
      80.                 }  
      81.   
      82.             }  
      83.   
      84. " and ").append(fieldName).append("=").append(fieldValue);  
      85.         }  
      86.   
      87. return sb.toString();  
      88.     }  
      89.   
      90. }


      使用到的两个注解类:

      1. <span style="font-size:18px;">package dao;  
      2.   
      3. import java.lang.annotation.ElementType;  
      4. import java.lang.annotation.Retention;  
      5. import java.lang.annotation.RetentionPolicy;  
      6. import java.lang.annotation.Target;  
      7.   
      8. /**
      9.  * Created by raid on 2016/5/14.
      10.  */  
      11. @Target({ElementType.TYPE})  
      12. @Retention(RetentionPolicy.RUNTIME)  
      13. public @interface Table {  
      14.     String value();  
      15. }  
      16. </span>



      1. package dao;  
      2.   
      3. import java.lang.annotation.ElementType;  
      4. import java.lang.annotation.Retention;  
      5. import java.lang.annotation.RetentionPolicy;  
      6. import java.lang.annotation.Target;  
      7.   
      8. /**
      9.  * Created by raid on 2016/5/14.
      10.  */  
      11. @Target({ElementType.FIELD})  
      12. @Retention(RetentionPolicy.RUNTIME)  
      13. public @interface Column {  
      14.     String value();  
      15. }





      1. package dao;  
      2.   
      3. /**
      4.  * Created by raid on 2016/5/14.
      5.  */  
      6. @Table("user")  
      7. public class Filter {  
      8.   
      9. @Column("id")  
      10. private int id;  
      11.   
      12. @Column("user_name")  
      13. private String userName;  
      14.   
      15. @Column("nick_name")  
      16. private String nickName;  
      17.   
      18. @Column("age")  
      19. private int age;  
      20.   
      21. @Column("city")  
      22. private String city;  
      23.   
      24. @Column("email")  
      25. private String email;  
      26.   
      27. @Column("mobile")  
      28. private String mobile;  
      29.   
      30. public int getId() {  
      31. return id;  
      32.     }  
      33.   
      34. public void setId(int id) {  
      35. this.id = id;  
      36.     }  
      37.   
      38. public String getUserName() {  
      39. return userName;  
      40.     }  
      41.   
      42. public void setUserName(String userName) {  
      43. this.userName = userName;  
      44.     }  
      45.   
      46. public String getNickName() {  
      47. return nickName;  
      48.     }  
      49.   
      50. public void setNickName(String nickName) {  
      51. this.nickName = nickName;  
      52.     }  
      53.   
      54. public int getAge() {  
      55. return age;  
      56.     }  
      57.   
      58. public void setAge(int age) {  
      59. this.age = age;  
      60.     }  
      61.   
      62. public String getCity() {  
      63. return city;  
      64.     }  
      65.   
      66. public void setCity(String city) {  
      67. this.city = city;  
      68.     }  
      69.   
      70. public String getEmail() {  
      71. return email;  
      72.     }  
      73.   
      74. public void setEmail(String email) {  
      75. this.email = email;  
      76.     }  
      77.   
      78. public String getMobile() {  
      79. return mobile;  
      80.     }  
      81.   
      82. public void setMobile(String mobile) {  
      83. this.mobile = mobile;  
      84.     }  
      85. }

      demo类:

      1. package dao;  
      2.   
      3. import java.lang.reflect.Field;  
      4. import java.lang.reflect.Method;  
      5.   
      6. /**
      7.  * Created by raid on 2016/5/14.
      8.  */  
      9. public class Test {  
      10.   
      11. public static void main(String[] args) {  
      12. new Filter();  
      13. 10);//查询ID为10的用户  
      14.   
      15. new Filter();  
      16. "lucy");  
      17.   
      18. new Filter();  
      19. "123@12.com,456@45.com,789@78.com");//查询邮箱为其中任意一个  
      20.   
      21.         String sql1 = query(f1);  
      22.         String sql2 = query(f2);  
      23.         String sql3 = query(f3);  
      24.   
      25.         System.out.println(sql1);;  
      26.         System.out.println(sql2);;  
      27.         System.out.println(sql3);;  
      28.     }  
      29.   
      30. private static String query(Filter f) {  
      31. new StringBuilder();  
      32. //1.获取到class  
      33.         Class c = f.getClass();  
      34. //2.获取到table的名字  
      35. boolean exists = c.isAnnotationPresent(Table.class);  
      36. if (!exists) {  
      37. return null;  
      38.         }  
      39. class);  
      40.   
      41.         String tableName = t.value();  
      42.   
      43. "select * from ").append(tableName).append(" where 1=1");  
      44.   
      45. //2.遍历所有的字段  
      46.         Field[] fArray = c.getDeclaredFields();  
      47. for (Field field : fArray) {  
      48. //4.处理每个字段对应的sql  
      49. //4.1拿到字段名  
      50. boolean fExists = field.isAnnotationPresent(Column.class);  
      51. if (!fExists) {  
      52. continue;  
      53.             }  
      54. class);  
      55.             String columName = column.value();  
      56. //4.2拿到字段值  
      57.             String fieldName = field.getName();  
      58. "get" + fieldName.substring(0,1).toUpperCase() + fieldName.substring(1);  
      59. null;  
      60. try {  
      61.                 Method getMethod = c.getMethod(getMethodName);  
      62.                 fieldValue = getMethod.invoke(f);  
      63. catch (Exception e) {  
      64.                 e.printStackTrace();  
      65.             }  
      66. //4.3拼装sql  
      67. if (fieldValue == null || (fieldValue instanceof Integer && (Integer)fieldValue == 0)) {  
      68. continue;  
      69.             }  
      70. if (fieldValue instanceof String) {  
      71. if (((String)fieldValue).contains(",")) {  
      72. ",");  
      73. " in(";  
      74. for (String v : values) {  
      75. "'" + v + "'" + ",";  
      76.                     }  
      77. 0, ((String) fieldValue).length()-1) + ")";  
      78. else {  
      79. "'" + fieldValue + "'";  
      80.                 }  
      81.   
      82.             }  
      83.   
      84. " and ").append(fieldName).append("=").append(fieldValue);  
      85.         }  
      86.   
      87. return sb.toString();  
      88.     }  
      89.   
      90. }