标签:initial str close return pass gen init finally text
package cn.bdqn.basedao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
/**
* Dao层的公共属性和方法
*/
public class BaseDao {
// 公共的属性
protected Connection connection = null;
protected PreparedStatement ps = null;
protected ResultSet rs = null;
// 连接数据库的四要素
/*
* protected String url = ConfigManage.getInstance().getValues("url");
* protected String user = ConfigManage.getInstance().getValues("user");
* protected String password = ConfigManage.getInstance()
* .getValues("password"); protected String driverClass =
* ConfigManage.getInstance().getValues( "driverClass");
*/
/*
* 连接数据库
*/
public boolean getConnection() {
try {
// 初始化上下文对象
Context context = new InitialContext();
DataSource source = (DataSource) context
.lookup("java:comp/env/jdbc/news");
connection = source.getConnection();
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
return true;
}
/*
* 关闭资源
*/
public void closeConnection() {
try {
if (rs != null) {
rs.close();
}
if (ps != null) {
ps.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 增删改
*/
public int executeUpdate(String sql, Object... params) {
int row = 0;// 影响的行数
if (getConnection()) {
try {
ps = connection.prepareStatement(sql);
if (params != null) {
// 遍历数组
for (int i = 0; i < params.length; i++) {
ps.setObject(i + 1, params[i]);
}
}
// 没有参数的情况
row = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭资源
closeConnection();
}
}
return row;
}
/*
* 查询
*/
public ResultSet executeQuery(String sql, Object... params) {
// 先做是否获取到连接的判断
if (getConnection()) {
try {
ps = connection.prepareStatement(sql);// 执行sql
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);// 拿到参数
}
}
rs = ps.executeQuery();// 没有带参数的
} catch (SQLException e) {
e.printStackTrace();
}// 这里就不关资源了,因为关了的话,实现类进行后续操作,就会拿不到连接,把关闭连接放在实现类中
}
return rs;
}
}
标签:initial str close return pass gen init finally text
原文地址:http://www.cnblogs.com/javaxiaodoufu/p/7464591.html