1.DButil
import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.ResourceBundle; /** * 数据库操作工具类 * @author xrhou * */ public class DBUtils { //数据库连接地址 public static String URL; //用户名 public static String USERNAME; //密码 public static String PASSWORD; //mysql的驱动类 public static String DRIVER; private static ResourceBundle rb = ResourceBundle.getBundle("com.xrhou.util.db.db-config"); private DBUtils(){} //使用静态块加载驱动程序 static{ URL = rb.getString("jdbc.url"); USERNAME = rb.getString("jdbc.username"); PASSWORD = rb.getString("jdbc.password"); DRIVER = rb.getString("jdbc.driver"); try { Class.forName(DRIVER); } catch (ClassNotFoundException e) { e.printStackTrace(); } } //定义一个获取数据库连接的方法 public static Connection getConnection(){ Connection conn = null; try { conn = DriverManager.getConnection(URL, USERNAME, PASSWORD); } catch (SQLException e) { e.printStackTrace(); System.out.println("获取连接失败"); } return conn; } /** * 关闭数据库连接 * @param rs * @param stat * @param conn */ public static void close(ResultSet rs,Statement stat,Connection conn){ try { if(rs!=null)rs.close(); if(stat!=null)stat.close(); if(conn!=null)conn.close(); } catch (SQLException e) { e.printStackTrace(); } } }
2.JdbcTemplete
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JdbcTemplete { /** * 实现增删改的抽象 * @param sql * @param args */ public int update(String sql,Object... args){ Connection conn = null; PreparedStatement ps = null; try{ conn = DBUtils.getConnection(); ps = conn.prepareStatement(sql); //设置占位符的参数 if(args!=null){ for (int i = 0; i < args.length; i++) { ps.setObject(i+1, args[i]); } } return ps.executeUpdate(); }catch(SQLException e){ e.printStackTrace(); return -1; }finally{ DBUtils.close(null, ps, conn); } } /** * 查询方法的抽象 * @param sql * @param handler * @param args * @return */ public Object query(String sql,ResultSetHandler handler,Object... args){ Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; try { conn = DBUtils.getConnection(); ps = conn.prepareStatement(sql); if(args!=null){ for (int i = 0; i < args.length; i++) { ps.setObject(i+1, args[i]); } } rs = ps.executeQuery(); return handler.doHandler(rs); } catch (SQLException e) { e.printStackTrace(); return null; } } }
3.ResultSetHandler处理
import java.sql.ResultSet; import java.sql.SQLException; public interface ResultSetHandler { public Object doHandler(ResultSet rs) throws SQLException; }
4.属性文件
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/friends jdbc.username=root jdbc.password=root
原文:http://www.cnblogs.com/xrhou12326/p/4335606.html