/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.beforespring.template; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Administrator */ public class Template { public void executeWithNativeMethod(MyJDBCCallback myJDBCCallback){ Connection connection=null; PreparedStatement ps=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/test"); myJDBCCallback.doInJDBC(connection,ps,rs); connection.commit(); } catch (Exception e) { e.printStackTrace(); }finally{ if(rs!=null){ try { rs.close(); } catch (SQLException ex) { } rs=null; } if(ps!=null){ try { ps.close(); } catch (SQLException ex) { } ps=null; } if(connection!=null){ try { connection.close(); } catch (SQLException ex) { } connection=null; } } } }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.beforespring.template; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; /** * * @author Administrator */ public interface MyJDBCCallback { public void doInJDBC(Connection connection,PreparedStatement ps,ResultSet rs); }
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.beforespring.template; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; /** * * @author Administrator */ public class OperationDB { public void saveUser(final User user){ new Template().executeWithNativeMethod(new MyJDBCCallback() { public void doInJDBC(Connection connection, PreparedStatement ps, ResultSet rs) { try { ps = connection.prepareStatement(""); ps.execute(); } catch (SQLException ex) { } } }); }}