import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
public class BaseDao {
// 使用log4j記錄日志
private static Logger logger = Logger.getLogger(BaseDao.class);
// 連接驅(qū)動
private static final String DRIVER = "oracle.jdbc.driver.OracleDriver";
// 連接路徑
private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
// 用戶名
private static final String USERNAME = "scott";
// 密碼
private static final String PASSWORD = "tiger";
//靜態(tài)代碼塊
static {
try {
// 加載驅(qū)動
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 獲取數(shù)據(jù)庫連接
*/
public Connection getConnection() {
Connection conn = null;
logger.debug("開始連接數(shù)據(jù)庫");
try{
conn=DriverManager.getConnection(URL, USERNAME, PASSWORD);
}catch(SQLException e){
e.printStackTrace();
logger.error("數(shù)據(jù)庫連接失?。?);
}
logger.debug("數(shù)據(jù)庫連接成功");
return conn;
}
/*
* 關(guān)閉數(shù)據(jù)庫連接,注意關(guān)閉的順序
*/
public void close(ResultSet rs, PreparedStatement ps, Connection conn) {
if(rs!=null){
try{
rs.close();
rs=null;
}catch(SQLException e){
e.printStackTrace();
logger.error("關(guān)閉ResultSet失敗");
}
}
if(ps!=null){
try{
ps.close();
ps=null;
}catch(SQLException e){
e.printStackTrace();
logger.error("關(guān)閉PreparedStatement失敗");
}
}
if(conn!=null){
try{
conn.close();
conn=null;
}catch(SQLException e){
e.printStackTrace();
logger.error("關(guān)閉Connection失敗");
}
}
}
}