import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* database tool class
*
* @author -
*
*/
public class DBUtils {
private static final ComboPooledDataSource POOL = new ComboPooledDataSource();
/**
* privatization constructor
*
* @author -
*/
private DBUtils() {
}
/**
* get ComboPooledDataSource object
*
* @return
* @author -
*/
public static ComboPooledDataSource getDataSource() {
return POOL;
}
/**
* get Connection object
*
* @return Connection
* @author -
*/
public static Connection getConnection() {
Connection conn = null;
try {
conn = POOL.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* close database connection
*
* @author -
* @param rs
* @param pstmt
* @param conn
*/
public static void connectionColse(ResultSet rs, PreparedStatement pstmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (pstmt != null) {
pstmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* get an QueryRunner object
*
* @author -
* @param pool
* @return QueryRunner
*/
public static QueryRunner getRunner() {
QueryRunner runner = new QueryRunner(POOL);
return runner;
}
/**
* select data from database
*
* @author -
* @param runner
* @param sql
* @param blh
* @throws SQLException
*/
public static <T> void ShowData(QueryRunner runner, String sql, BeanListHandler<T> blh) throws SQLException {
List<T> queryList = runner.query(sql, blh);
for (Object obj : queryList) {
System.out.println(obj);
}
}
/**
* select data from database and return bean object
*
* @param runner
* @param sql
* @param bh
* @return T
* @throws SQLException
*/
public static <T> T SelectData(QueryRunner runner, String sql, BeanHandler<T> bh, Object... obj)
throws SQLException {
T t = runner.query(sql, bh, obj);
return t;
}
/**
* update data and return the number of affected rows
*
* @param runner
* @param sql
* @param params
* @return int
* @throws SQLException
*/
public static int UpdateData(QueryRunner runner, String sql, Object... params) throws SQLException {
int count = runner.update(sql, params);
return count;
}
/**
* close database connection pool
*
* @author -
* @param pool
*/
public static void poolColse(ComboPooledDataSource pool) {
if (pool != null) {
pool.close();
}
}
}
DBUtils工具类编写
猜你喜欢
转载自blog.csdn.net/AnameJL/article/details/107403203
今日推荐
周排行