Remove boilerplate from db code

后端 未结 5 1077
深忆病人
深忆病人 2021-01-12 09:17

It seems that every time I want to perform a db query, I have to write the following:

Connection conn = null;
Statement stmt = null;
ResultSet rset = null;

         


        
5条回答
  •  温柔的废话
    2021-01-12 10:08

    Make a helper method?

    public class DBHelper
    {
        public static Object run(string sql, List params, ResultHandler rhandler)
        {
            Connection conn = null;
            Statement stmt = null;
            ResultSet rset = null;
    
            try {
                conn = dataSource.getConnection();
                stmt = conn.prepareStatement(sql);
                int i = 0;
                for(Object p in params)
                {
                    stmt.setObject(++i, p);
                }
                rset = stmt.executeQuery();
                return rhandler.handle(rset);
            } finally {
                    try { rset.close(); } catch(Exception e) { }
                    try { stmt.close(); } catch(Exception e) { }
                    try { conn.close(); } catch(Exception e) { }
            }
        }
    }
    
    public interface ResultHandler
    {
        public Object handle(ResultSet)
    }
    
    public class Test
    {
        public static void main(String[] args)
        {
            String s = (String)DBHelper.run("select * from mytable where col = ?",
                    Arrays.asList({"foo"}), 
                    new ResultHandler
                    {
                        public Object handle(ResultSet r)
                        {
                            r.first();
                            return r.getString("col2");
                        }
                    }();
        }
    }
    

提交回复
热议问题