DbUtil—操作数据库的方法

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();
}
}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值