JDBC 简单封装 工具类
JDBC配置文件
#============================#
#===== Database sttings =====#
#============================#
#mysql database setting
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/database?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=root
JDBCUtil
public class JDBCUtil {
// 日志接口
private static Logger logger = LoggerFactory.getLogger(JDBCUtil.class);
//JDBC配置属性
private static Properties ps = new Properties();
// 配置文件位置
private static final String db_setting = "/config/acs-db.properties";
// 初始化JDBC配置文件属性
static{
try {
if(JDBCUtil.class.getResourceAsStream(db_setting) == null){
if(logger.isInfoEnabled())logger.info("请调用 getInstance(clazz) 方法! ");
}else{
ps.load(JDBCUtil.class.getResourceAsStream(db_setting));
// 加载JDBC驱动
Class.forName(ps.getProperty("jdbc.driver"));
if(logger.isInfoEnabled())logger.info("JDBC驱动启动成功! "+ps.getProperty("jdbc.driver"));
}
} catch (IOException | ClassNotFoundException e) {
logger.error(e.getMessage(),e);
}
}
private JDBCUtil(){}
private static JDBCUtil jdbcUtil = new JDBCUtil();
/**
*
* getInstance(获取JDBCUtil实例)
* (注意事项:同项目下调用 – 可选)
* @return
* @exception
* @since 1.0.0
*/
public static JDBCUtil getInstance(){
return jdbcUtil;
}
/**
* getInstance(获取JDBCUtil实例)
* (注意事项:不同项目下调用 – 可选)
* @param clazz 调用类字节码
* @return
* @throws IOException
* @exception
* @since 1.0.0
*/
public static JDBCUtil getInstance(Class<?> clazz) throws IOException{
if(clazz.getResourceAsStream(db_setting) == null)
throw new RuntimeException("acs-db.properties is not found ") ;
ps.load(clazz.getResourceAsStream(db_setting));
// 加载JDBC驱动
try {
Class.forName(ps.getProperty("jdbc.driver"));
} catch (ClassNotFoundException e) {
logger.error(e.getMessage(),e);
}
return jdbcUtil;
}
/**
*
* getConnection(获取数据库连接)
* (注意事项:-无)
* @return
* @exception
* @since 1.0.0
*/
public Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(ps.getProperty("jdbc.url"),
ps.getProperty("jdbc.username"), ps.getProperty("jdbc.password"));
} catch (SQLException e) {
logger.error(e.getMessage(),e);
}
return conn;
}
// JDBC BASE DAO
private BaseDaoJdbc baseDaoJdbc = new BaseDaoJdbcimpl();
/**
* getBaseDaoJdbc(获取原始的JDBC Dao 层)
* (注意事项:-无)
* @return
* @exception
* @since 1.0.0
*/
public BaseDaoJdbc getBaseDaoJdbc (){
return baseDaoJdbc;
}
/**
*
* query(查询方法)
* (注意事项: – 目前只支持 Map List返回值)
* @param resultClass 返回类型 如: Map.class
* @return
* @throws SQLException
* @exception
* @since 1.0.0
*/
public <E> E query (String sql,Class<E> resultClass,Object ... obj){
ResultSet rs = baseDaoJdbc.queryAll(sql, getConnection(), obj);
try {
if(resultClass == Map.class){
if(rs.next()) return (E) getResultMap(rs);
}else if(resultClass == List.class){
return (E) getResultList(rs);
}else{
throw new RuntimeException(""+resultClass +" 该类型目前还没有做扩展!");
}
} catch (SQLException e) {
logger.error(e.getMessage(),e);
}finally{
try {
baseDaoJdbc.closeAll(rs, rs.getStatement(), rs.getStatement().getConnection());
} catch (SQLException e) {
logger.error(e.getMessage(),e);
}
if(logger.isInfoEnabled())logger.info("关闭数据库连接!");
}
return null;
}
/**
*
* executeUpdate(增加、修改、删除 操作)
* (注意事项:无)
* @param sql
* @param obj
* @return
* @exception
* @since 1.0.0
*/
public int executeUpdate(String sql,Object ...obj){
int k = 0;
k = getBaseDaoJdbc().executeUpdate(sql, getConnection(), obj);
return k;
}
/*
* 解析ResultSet 表列数据
*/
private Map<String,Object> getResultMap(ResultSet rs) throws SQLException{
Map<String, Object> rawMap = new HashMap<String, Object>();
ResultSetMetaData rsmd = rs.getMetaData(); // 表对象信息
int count = rsmd.getColumnCount(); // 列数
// 遍历之前需要调用 next()方法
for (int i = 1; i <= count; i++) {
String key = rsmd.getColumnLabel(i);
Object value = rs.getObject(key);
rawMap.put(key, value);
}
return rawMap;
}
/*
* 解析ResultSet 表数据
*/
private List<Map<String,Object>> getResultList(ResultSet rs) throws SQLException{
List<Map<String,Object>> rawList = new ArrayList<Map<String,Object>>();
while(rs.next()){
Map<String, Object> rawMap = getResultMap(rs);
rawList.add(rawMap);
}
return rawList;
}
}
BaseDaoJdbc
public interface BaseDaoJdbc {
/**
* 关闭所有连接
* @param conn
* @param stmt
* @param rst
* @return
*/
public boolean closeAll(ResultSet rst,Statement stmt , Connection conn);
/**
* 关闭连接对象
* @param conn
* @return
*/
public boolean closeConnection(Connection conn);
/**
* 关闭执行sql对象
* @param stmt
* @return
*/
public boolean closeStatement(Statement stmt);
/**
* 关闭结果集
* @param rst
* @return
*/
public boolean closeResultSet(ResultSet rst);
/**
* 增删改
* @param sql
* @param conn
* @param obj
* @return
*/
public int executeUpdate(String sql,Connection conn,Object...obj);
/**
* 查询所有
* @param sql
* @param conn
* @param obj
* @return
*/
public ResultSet queryAll(String sql,Connection conn, Object... obj);
}
BaseDaoJdbcImpl
public class BaseDaoJdbcimpl implements BaseDaoJdbc {
public boolean closeAll(ResultSet rst,Statement stmt , Connection conn) {
// TODO 关闭所有连接
boolean flag = false;
try {
if(rst!=null){
rst.close();
}
if(stmt!=null){
stmt.close();
}
if(conn!=null&&!conn.isClosed()){
conn.close();
flag = true;
}
} catch (SQLException e) {
e.printStackTrace();
}
return flag;
}
public boolean closeConnection(Connection conn) {
// TODO 关闭Connection对象
try {
if(conn!=null&&!conn.isClosed()){
try {
conn.close();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return false;
}
public boolean closeResultSet(ResultSet rst) {
// TODO 关闭ResultSet对象
if(rst!=null){
try {
rst.close();
return true;
} catch (SQLException e) {
e.printStackTrace();
}
}
return false;
}
public boolean closeStatement(Statement stmt) {
// TODO 关闭Statement 对象
if(stmt!=null){
if(stmt instanceof PreparedStatement){
try {
((PreparedStatement) stmt).close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return false;
}
/**
* 增删改
* @param sql
* @param obj
* @return
*/
public int executeUpdate(String sql,Connection conn,Object...obj){
int i = 0 ;
PreparedStatement psts = null ;
try {
psts = conn.prepareStatement(sql) ;
if(obj!=null && obj.length>0){
for(int j=0;j<obj.length;j++){
psts.setObject((j+1), obj[j]) ;
}
}
i = psts.executeUpdate() ;
} catch (SQLException e) {
e.printStackTrace();
}finally{
closeAll(null, psts, conn);
}
return i ;
}
/**
* 查询所有
* @param sql
* @param obj
* @return ResultSet
*/
public ResultSet queryAll(String sql,Connection conn, Object... obj) {
PreparedStatement psts = null ;
ResultSet rs = null ;
try {
psts = conn.prepareStatement(sql) ;
if(obj!=null && obj.length>0){
for(int j=0;j<obj.length;j++){
psts.setObject((j+1), obj[j]) ;
}
}
rs = psts.executeQuery() ;
} catch (SQLException e) {
e.printStackTrace();
}
return rs ;
}
使用也很简单:
public static void main(String[] args) throws SQLException {
JDBCUtil JdbcUtil = JDBCUtil.getInstance();
User user = initUser();
// 新增操作
int i = JdbcUtil.executeUpdate("insert into user values(?,?,?,?,?)"
,user.getId(),user.getName(),user.getAge(),user.getBirthday(),user.getMoney());
System.out.println("是否成功:"+i);
// 查询
List list = JdbcUtil.query("select * from user ", List.class);
System.out.println(list);
}
private static User initUser(){
User user = new User();
user.setId(UUID.randomUUID().toString());
user.setName("马尔代夫");
user.setAge(38);
user.setBirthday(new Date());
user.setMoney(1366.3);
return user;
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。