一个简单的SQL语句拼装代码

http://blog.csdn.net/njchenyi/article/details/6691790


本人很懒,非常不想写那些SQL语句,特别是要和列名和值的顺序要一一对应,万一出点错查起来很困难。反正对性能没啥很高要求,那就随手写了个自己拼装SQL语句的代码。

用的c3p0数据库连接池,只完成了单表的增删改查操作,不支持多表操作。


  • 插入操作接口add(String tableName, HashMap<String, String> values)。tableName就是要做操作的表名,values是插入时需要设置的值,采用名值对方式放入Map中。
  • 删除操作接口delete(String tableName, HashMap<String, String> conditions)。tableName就是要做操作的表名,conditions是删除时对应的条件,采用名值对方式放入Map中。
  • 更新操作接口update(String tableName, HashMap<String, String> values, HashMap<String, String> conditions)。tableName就是要做操作的表名,values是更新时需要设置的值,采用名值对方式放入Map中,conditions是更新时对应的条件,采用名值对方式放入Map中。
  • 查询操作接口select(String tableName, HashMap<String, String> conditions)。tableName就是要做操作的表名,conditions是查询时对应的条件,采用名值对方式放入Map中。


  1. import java.sql.*;  
  2. import java.util.*;  
  3.   
  4.   
  5. /** 
  6.  * 
  7.  * @author Chen Yi <njchenyi@gmail.com> 
  8.  */  
  9. public class DatabaseOperate {  
  10.   
  11.   
  12. //    String dirverClass = "com.mysql.jdbc.Driver";  
  13. //    String url = "jdbc:mysql://10.45.7.23:3306/gztr_ema?autoReconnect=true";  
  14. //    String username = "root";  
  15. //    String password = "rootroot";  
  16. //    int minPoolSize = 3;  
  17. //    int maxPoolSize = 15;  
  18.     public ConnectionManager cm = null;  
  19.   
  20.   
  21. //    /**  
  22. //     *  
  23. //     * @throws Exception  
  24. //     */  
  25. //    public DatabaseOperate() throws Exception {  
  26. //        cm = ConnectionManager.createConnectionManager(dirverClass, url, username, password, maxPoolSize, minPoolSize);  
  27. //    }  
  28.   
  29.   
  30.     /** 
  31.      * 
  32.      * @param dirverClass 
  33.      * @param url 
  34.      * @param username 
  35.      * @param password 
  36.      * @param maxPoolSize 
  37.      * @param minPoolSize 
  38.      * @throws Exception 
  39.      */  
  40.     public DatabaseOperate(String dirverClass, String url, String username, String password, int maxPoolSize, int minPoolSize) throws Exception {  
  41.         cm = ConnectionManager.createConnectionManager(dirverClass, url, username, password, maxPoolSize, minPoolSize);  
  42.     }  
  43.   
  44.   
  45.     /** 
  46.      * 增加记录 
  47.      * @param tableName 
  48.      * @param values 
  49.      * @return int 插入后返回插入行的记录 
  50.      * @throws SQLException  
  51.      */  
  52.     public int add(String tableName, HashMap<String, String> values) throws SQLException {  
  53.         Connection conn = null;  
  54.         Statement stmt = null;  
  55.         ResultSet rs = null;  
  56.         int index = -1;  
  57.         try {  
  58.             StringBuilder sql = new StringBuilder();  
  59.   
  60.   
  61.             StringBuilder column = new StringBuilder();  
  62.             StringBuilder data = new StringBuilder();  
  63.             if ((values != null) && !values.isEmpty()) {  
  64.                 Set<String> input = values.keySet();  
  65.                 Iterator<String> it = input.iterator();  
  66.   
  67.   
  68.                 for (; it.hasNext();) {  
  69.                     String s = it.next();  
  70.                     column.append(s);  
  71. //                data.append("'");  
  72.                     data.append(values.get(s));  
  73.                     if (it.hasNext()) {  
  74.                         column.append(", ");  
  75.                         data.append(" , ");  
  76.                     }  
  77.                 }  
  78.             } else {  
  79.                 throw new SQLException(" values can not be empty or null");  
  80.             }  
  81.             sql.append("INSERT INTO ");  
  82.             sql.append(tableName);  
  83.             sql.append(" (");  
  84.             sql.append(column);  
  85.             sql.append(") VALUES ( ");  
  86.             sql.append(data);  
  87.             sql.append(")");  
  88.             System.out.println(sql.toString());  
  89.   
  90.   
  91.             conn = cm.getConnection();  
  92.             stmt = conn.createStatement();  
  93.             stmt.execute(sql.toString());  
  94.   
  95.   
  96.             rs = stmt.executeQuery("SELECT LAST_INSERT_ID()");  
  97.             if (rs.next()) {  
  98.                 index = rs.getInt(1);  
  99.             }  
  100.             return index;  
  101.         } catch (SQLException e) {  
  102. //            e.printStackTrace();  
  103.             throw e;  
  104.         } finally {  
  105.             if (rs != null) {  
  106.                 try {  
  107.                     rs.close();  
  108.                 } catch (Exception e) {  
  109.                 }  
  110.             }  
  111.             if (stmt != null) {  
  112.                 try {  
  113.                     stmt.close();  
  114.                 } catch (Exception e) {  
  115.                 }  
  116.             }  
  117.             if (conn != null) {  
  118.                 try {  
  119.                     conn.close();  
  120.                 } catch (Exception e) {  
  121.                 }  
  122.             }  
  123.         }  
  124.     }  
  125.   
  126.   
  127.     /** 
  128.      * 删除记录 
  129.      * @param tableName 
  130.      * @param conditions 
  131.      * @throws SQLException  
  132.      */  
  133.     public void delete(String tableName, HashMap<String, String> conditions) throws SQLException {  
  134.         Connection conn = null;  
  135.         Statement stmt = null;  
  136.         try {  
  137.             StringBuilder sql = new StringBuilder();  
  138.             sql.append("DELETE FROM ");  
  139.             sql.append(tableName);  
  140.             if ((conditions != null) && !conditions.isEmpty()) {  
  141.                 Set<String> input = conditions.keySet();  
  142.                 Iterator<String> it = input.iterator();  
  143.                 StringBuilder condition = new StringBuilder();  
  144.   
  145.   
  146.                 for (; it.hasNext();) {  
  147.                     String s = it.next();  
  148.                     condition.append(s);  
  149.                     condition.append(" = ");  
  150.                     condition.append(conditions.get(s));  
  151.                     if (it.hasNext()) {  
  152.                         condition.append(" AND ");  
  153.                     }  
  154.                 }  
  155.                 sql.append(" WHERE ");  
  156.                 sql.append(condition);  
  157.             } else {  
  158.                 throw new SQLException(" conditions can not be empty or null");  
  159.             }  
  160.             System.out.println(sql.toString());  
  161.   
  162.   
  163.             conn = cm.getConnection();  
  164.             stmt = conn.createStatement();  
  165.             stmt.execute(sql.toString());  
  166.         } catch (SQLException e) {  
  167. //            e.printStackTrace();  
  168.             throw e;  
  169.         } finally {  
  170.             if (stmt != null) {  
  171.                 try {  
  172.                     stmt.close();  
  173.                 } catch (Exception e) {  
  174.                 }  
  175.             }  
  176.             if (conn != null) {  
  177.                 try {  
  178.                     conn.close();  
  179.                 } catch (Exception e) {  
  180.                 }  
  181.             }  
  182.         }  
  183.     }  
  184.   
  185.   
  186.     /** 
  187.      * 更新记录 
  188.      * @param tableName 
  189.      * @param values 
  190.      * @param conditions 
  191.      * @throws SQLException  
  192.      */  
  193.     public void update(String tableName, HashMap<String, String> values, HashMap<String, String> conditions) throws SQLException {  
  194.         Connection conn = null;  
  195.         Statement stmt = null;  
  196.         ResultSet rs = null;  
  197.         try {  
  198.             StringBuilder sql = new StringBuilder();  
  199.             sql.append("UPDATE ");  
  200.             sql.append(tableName);  
  201.             sql.append(" SET ");  
  202.             if ((values != null) && !values.isEmpty()) {  
  203.                 Set<String> input = values.keySet();  
  204.                 Iterator<String> it = input.iterator();  
  205.   
  206.   
  207.                 StringBuilder data = new StringBuilder();  
  208.                 for (; it.hasNext();) {  
  209.                     String s = it.next();  
  210.   
  211.   
  212.                     data.append(s + " = " + values.get(s));  
  213.                     if (it.hasNext()) {  
  214.                         data.append(",");  
  215.                     }  
  216.                 }  
  217.                 sql.append(data);  
  218.             } else {  
  219.                 throw new SQLException(" values can not be empty or null");  
  220.             }  
  221.             if (((conditions != null) && !conditions.isEmpty())) {  
  222.                 Set<String> input = conditions.keySet();  
  223.                 Iterator<String> it = input.iterator();  
  224.                 StringBuilder condition = new StringBuilder();  
  225.   
  226.   
  227.                 for (; it.hasNext();) {  
  228.                     String s = it.next();  
  229.                     condition.append(s);  
  230.                     condition.append(" = ");  
  231.                     condition.append(conditions.get(s));  
  232.                     if (it.hasNext()) {  
  233.                         condition.append(" AND ");  
  234.                     }  
  235.                 }  
  236.                 sql.append(" WHERE ");  
  237.                 sql.append(condition);  
  238.             } else {  
  239.                 throw new SQLException(" conditions can not be empty or null");  
  240.             }  
  241.   
  242.   
  243.   
  244.   
  245.             System.out.println(sql.toString());  
  246.   
  247.   
  248.             conn = cm.getConnection();  
  249.             stmt = conn.createStatement();  
  250.             stmt.execute(sql.toString());  
  251.   
  252.   
  253.         } catch (SQLException e) {  
  254.             throw e;  
  255.         } finally {  
  256.             if (rs != null) {  
  257.                 try {  
  258.                     rs.close();  
  259.                 } catch (Exception e) {  
  260.                 }  
  261.             }  
  262.             if (stmt != null) {  
  263.                 try {  
  264.                     stmt.close();  
  265.                 } catch (Exception e) {  
  266.                 }  
  267.             }  
  268.             if (conn != null) {  
  269.                 try {  
  270.                     conn.close();  
  271.                 } catch (Exception e) {  
  272.                 }  
  273.             }  
  274.         }  
  275.     }  
  276.   
  277.   
  278.     /** 
  279.      * 查询记录 
  280.      * @param tableName 
  281.      * @param conditions 
  282.      * @return 
  283.      * @throws SQLException  
  284.      */  
  285.     public Results select(String tableName, HashMap<String, String> conditions) throws SQLException {  
  286.         Connection conn = null;  
  287.         Statement stmt = null;  
  288.         ResultSet rs = null;  
  289.         try {  
  290.             StringBuilder sql = new StringBuilder();  
  291.             sql.append("SELECT * FROM ");  
  292.             sql.append(tableName);  
  293.   
  294.   
  295.             if ((conditions != null) && !conditions.isEmpty()) {  
  296.                 Set<String> input = conditions.keySet();  
  297.                 Iterator<String> it = input.iterator();  
  298.                 StringBuilder condition = new StringBuilder();  
  299.   
  300.   
  301.                 for (; it.hasNext();) {  
  302.                     String s = it.next();  
  303.                     condition.append(s);  
  304.                     condition.append(" = ");  
  305.                     condition.append(conditions.get(s));  
  306.                     if (it.hasNext()) {  
  307.                         condition.append(" AND ");  
  308.                     }  
  309.                 }  
  310.                 sql.append(" WHERE ");  
  311.                 sql.append(condition);  
  312.             } else {  
  313.                   
  314.             }  
  315.             System.out.println(sql.toString());  
  316.   
  317.   
  318.             conn = cm.getConnection();  
  319.             stmt = conn.createStatement();  
  320.   
  321.   
  322.             rs = stmt.executeQuery(sql.toString());  
  323.   
  324.   
  325.             Results results = new Results();  
  326.             ResultSetMetaData rsm = rs.getMetaData(); //获得列集  
  327.             int col = rsm.getColumnCount();  //获得列的个数  
  328.             String colName[] = new String[col];  
  329.             //取结果集中的表头名称, 放在colName数组中  
  330.             for (int i = 0; i < col; i++) {   //-->第一列,从1开始.所以获取列名,或列值,都是从1开始  
  331.                 colName[i] = rsm.getColumnName(i + 1);  //-->获得列值的方式一:通过其序号  
  332. //                System.out.println(colName[i]);  
  333.             }//End for  
  334.             rs.last();  
  335.             int row = rs.getRow();  
  336.             rs.beforeFirst();  
  337.             String data[][] = new String[row][col];  
  338.             //取结果集中的数据, 放在data数组中  
  339.             for (int i = 0; i < row; i++) {  
  340.                 rs.next();  
  341.                 for (int j = 0; j < col; j++) {  
  342.                     data[i][j] = rs.getString(j + 1);  
  343. //                    System.out.print(data[i][j]);  
  344.                 }  
  345. //                System.out.println();  
  346.             }//End for  
  347.   
  348.   
  349.             results.setColumnName(colName);  
  350.             results.setData(data);  
  351. //            System.out.println(results.getDataRows());  
  352.             return results;  
  353.         } catch (SQLException e) {  
  354. //            e.printStackTrace();  
  355.             throw e;  
  356.         } finally {  
  357.             if (rs != null) {  
  358.                 try {  
  359.                     rs.close();  
  360.                 } catch (Exception e) {  
  361.                 }  
  362.             }  
  363.             if (stmt != null) {  
  364.                 try {  
  365.                     stmt.close();  
  366.                 } catch (Exception e) {  
  367.                 }  
  368.             }  
  369.             if (conn != null) {  
  370.                 try {  
  371.                     conn.close();  
  372.                 } catch (Exception e) {  
  373.                 }  
  374.             }  
  375.         }  
  376.     }  
  377.   
  378.   
  379. //    public static void main(String[] arg) {  
  380. //        try {  
  381. //            DatabaseOperate dl = new DatabaseOperate();  
  382. //            HashMap<String, String> values = new HashMap<String, String>();  
  383. //            values.put("coId", "1");  
  384.             dl.add("TMF.T_APP_Car",in);  
  385. //            HashMap<String, String> conditions = new HashMap<String, String>();  
  386. //            conditions.put("userCode", "'admin'");  
  387. //            conditions.put("coId", "'2'");  
  388.             dl.select("t_app_user", conditions);  
  389. //            dl.update("t_app_user", values, conditions);  
  390. //            //            System.out.println(rs.getRow());  
  391. //        } catch (Exception ex) {  
  392. //            ex.printStackTrace();  
  393. //        }  
  394. //    }  
  395.   
  396.   
  397.     public void close() {  
  398.         cm = null;  
  399.     }  
  400. }  


为了供多个模块共用,所以在最后close方法中没有调用cm.close()方法,这个根据需要自己添加吧。

main函数是我自己做简单测试用的,也可以当做例子。


另外还有个辅助类用于查询时使用

  1. /** 
  2.  * 
  3.  * @author Chen Yi <njchenyi@gmail.com> 
  4.  */  
  5. public class Results {  
  6.   
  7.     private String[] columnName = null;  
  8.     private String[][] data = null;  
  9.     int cursor = -1;  
  10.   
  11.     public int findColumnIndex(String name) {  
  12.         for (int i = 0; i < columnName.length; i++) {  
  13.             if (name.equals(columnName[i])) {  
  14.                 return i;  
  15.             }  
  16.         }  
  17.         return -1;  
  18.     }  
  19.   
  20.     public int getDataRows() {  
  21.         return data.length;  
  22.     }  
  23.   
  24.     public String getString(String columnName) throws Exception {  
  25.         int i = findColumnIndex(columnName);  
  26.         if (i < 0) {  
  27.             throw new Exception("Can not find column name: " + columnName);  
  28.         }  
  29.         return data[cursor][i];  
  30.     }  
  31.   
  32.     public boolean next() {  
  33.         if (data.length - cursor > 1) {  
  34.             cursor++;  
  35. //            System.out.println("cursor at: "+cursor);  
  36. //            if(cursor>=data.length){  
  37. //                cursor = -1;  
  38. //            }  
  39.             return true;  
  40.         } else {  
  41.             return false;  
  42.         }  
  43.     }  
  44.   
  45.     public void beforeFirst() {  
  46.         cursor = -1;  
  47.     }  
  48.   
  49.     public void afterLast() {  
  50.         cursor = data.length;  
  51.     }  
  52.   
  53.     public void clear() {  
  54.         cursor = -1;  
  55.         columnName = null;  
  56.         data = null;  
  57.     }  
  58.   
  59.     /** 
  60.      * @return the columnName 
  61.      */  
  62.     public String[] getColumnName() {  
  63.         return columnName;  
  64.     }  
  65.   
  66.     /** 
  67.      * @param columnName the columnName to set 
  68.      */  
  69.     public void setColumnName(String[] columnName) {  
  70.         this.columnName = columnName;  
  71.     }  
  72.   
  73.     /** 
  74.      * @return the data 
  75.      */  
  76.     public String[][] getData() {  
  77.         return data;  
  78.     }  
  79.   
  80.     /** 
  81.      * @param data the data to set 
  82.      */  
  83.     public void setData(String[][] data) {  
  84.         this.data = data;  
  85.     }  


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值