標籤:
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.Driverjdbc.url=jdbc:mysql://localhost:3306/friendsjdbc.username=rootjdbc.password=root
java實現的JDBCTemplate工具