一、增删改查通用类
public class BaseDao {
protected ResultSet rs = null;
protected Connection conn = null;
protected PreparedStatement ps = null;
/**
* 方法功能:通用增删改
*
* @param sql
* @param Object...objs
*/
public int executeUpdate(String sql, Object... objects) {
int n = 0;
try {
conn = DBUtils.getConn();
ps = conn.prepareStatement(sql);
for (int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
n = ps.executeUpdate();
} catch (Exception e) {
System.out.println("DAO增删改异常");
e.printStackTrace();
} finally {
DBUtils.myClose(conn, ps, null);
}
return n;
}
/**
* 方法功能:通用查询
*
* @param sql
* @param Object...objs
*/
public ResultSet executeQuery(String sql, Object... objects) {
try {
conn = DBUtils.getConn();
ps = conn.prepareStatement(sql);
for (int i = 0; i < objects.length; i++) {
ps.setObject(i + 1, objects[i]);
}
rs = ps.executeQuery();
} catch (Exception e) {
System.out.println("DAO查询异常");
e.printStackTrace();
}
return rs;
}
/**
* 方法功能:获取指定表的最大ID
* @param colID
* @param tableName
* @return
*/
public int getMaxID(String colID,String tableName) {
String sql = "select nvl(max("+colID+"),0) from "+tableName;
ResultSet rs = null;
try {
rs = this.executeQuery(sql);
if(rs.next()) {
return rs.getInt(1)+1;
}
} catch (Exception e) {
// TODO: handle exception
}
return 0;
}
/**
* 方法功能:获取任意表格的总记录数
* @param 表名
*/
public int getTableCount(String tableName) {
int count = 0;
String sql = "select count(*) from "+tableName;
ResultSet rs = this.executeQuery(sql);
try {
if(rs.next()) {
count= rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtils.myClose(this.conn, this.ps, rs);
}
return count;
}
public int getTableCount(String tableName ,int ntid) {
int count = 0;
String sql = "select count(*) from "+tableName;
if(ntid !=0 ) {
sql+=" where ntid = "+ntid;
}
ResultSet rs = this.executeQuery(sql);
try {
if(rs.next()) {
count= rs.getInt(1);
}
} catch (Exception e) {
e.printStackTrace();
}finally {
DBUtils.myClose(this.conn, this.ps, rs);
}
return count;
}
public static void main(String[] args) {
int count = new BaseDao().getTableCount("tb_news", 1);
System.out.println(count);
}
}
二、数据库帮助类
public class DBUtils {
// OracleDriver
private static final String CLASSNAME = "oracle.jdbc.driver.OracleDriver";
private static final String URL = "jdbc:oracle:thin:@localhost:1521:orcl";
/** 加载驱动 */
static {
try {
Class.forName(CLASSNAME);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*