public class DbUtil {
//获得数据库连接对象
protected Connection conn = null;
protected PreparedStatement stmt = null;
protected ResultSet rs = null;
//获得数据库连接对象
public Connection getcConnection(){
try {
Context context = new InitialContext();
DataSource ds = (DataSource)context.lookup("java:comp/env/jdbc/easybuy");
conn = ds.getConnection();
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
//增删改
public int executeUpdate(String sql, String[] params) {
int i = 0;
Connection conn = null;
PreparedStatement st = null;
try {
conn = getcConnection();
st = conn.prepareStatement(sql);
if (params != null) {
for (int j = 0; j < params.length; j++) {
st.setString(j + 1,params[j]);
}
}
i = st.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
closeAll();
}
return i;
}
//查询单个对象
public Object get(Class type, String sql, Object... params){
Object object = null;
QueryRunner runner = new QueryRunner();
// 数据库表中字段名(别名)和实体中属性名一致
ResultSetHandler handler = new BeanHandler(type);
Connection conn = getcConnection();
try {
object = runner.query(conn, sql, handler, params);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
DbUtils.close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
return object;
}
//查询集合
public List find(Class type, String sql, Object... params) {
List list = new ArrayList();
QueryRunner runner = new QueryRunner();
// 数据库表中字段名(别名)和实体中属性名一致
ResultSetHandler handler = new BeanListHandler(type);
Connection conn = getcConnection();
try {
list = runner.query(conn, sql, handler, params);
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
DbUtils.close(conn);
} catch (SQLException e) {
e.printStackTrace();
}
}
return list;
}
//关闭连接对象
public void closeAll(){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}