package com.yang.DAO;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
public class BaseDao {
private Connection conn = null;//连接对象
private PreparedStatement ps = null;//执行SQL语句
private ResultSet rs = null;//结果集
private static String driverClass;
private static String url;
private static String username;
private static String password;
static {
//静态代码块,性能高,只加载一次
try {
Properties p = new Properties();
p.load(BaseDao.class.getClassLoader().getResourceAsStream("jdbc.properties"));
driverClass = (String)p.get("driverClass");
url = (String)p.get("url");
username = (String)p.get("username");
password = (String)p.get("password");
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
}
/**
* 01-打开数据库连接
*/
public void openConn() {
try {
Class.forName(driverClass);
conn=DriverManager.getConnection(url,username,password);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 02-通用的执行增删改
*/
public int myexecuteUpdate(String sql,Object[] params) {
this.openConn();//打开数据库连接
try {
ps=conn.prepareStatement(sql);
if(params!=null) {
for(int i=0;i<params.length;i++) {
ps.setObject(i+1, params[i]);
}
}
return ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}finally {
this.closeConn();//关闭数据库
}
return 0;
}
/**
* 03-通用的执行查询的方法
*/
public ResultSet myexecuteQuery(String sql,Object[] params) {
this.openConn();
try {
ps=conn.prepareStatement(sql);
if(params!=null){
for (int i = 0; i < params.length; i++) {
ps.setObject(i+1, params[i]);
}
}
rs=ps.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}finally{
//查询的此处不能提前关闭数据库。不然话结果集合没法遍历
}
return rs;
}
/**
* 04-关闭数据库
*/
protected void closeConn() {
try {
if(rs!=null){
rs.close();
}
if(ps!=null){
ps.close();
}
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}