import java.sql.*;
import java.util.List;
/**
* 为数据库操作提供快捷方式。取连接、释放连接都包括在方法内,方便应用。
* @author
*/
public class DBUtils {
/**
* 查询单个对象
* @param sql 查询语句
* @return 查询结果(如果有多条记录,返回第一条)
*/
public static String getString(String sql) {
ConnectionObject co = ConnectionManager.getConnectionFactory().getConnection();
try {
ResultSet set = co.executeQuery(sql);
String obj = null;
try {
if (set.next())
obj = set.getString(1);
set.close();
return obj;
}catch(Throwable e){
throw new DBException(e);
}
}finally {
ConnectionManager.getConnectionFactory().freeConnection(co);
}
}
/**
* 查询单个对象
* @param sql 查询语句
* @return 查询结果(如果有多条记录,返回第一条)
*/
public static Object getObject(String sql) {
ConnectionObject co = ConnectionManager.getConnectionFactory().getConnection();
try {
ResultSet set = co.executeQuery(sql);
try {
Object obj = null;
if (set.next())
obj = set.getObject(1);
set.close();
return obj;
}catch(Throwable e){
throw new DBException(e);
}
}finally {
ConnectionManager.getConnectionFactory().freeConnection(co);
}
}
/**
* 查询单个对象
* @param sql 查询语句
* @return 查询结果(如果有多条记录,返回第一条)
*/
public static int getInt(String sql) {
ConnectionObject co = ConnectionManager.getConnectionFactory().getConnection();
try {
ResultSet set = co.executeQuery(sql);
try {
int obj = -1;
if (set.next())
obj = set.getInt(1);
set.close();
return obj;
}catch(Throwable e){
throw new DBException(e);
}
}finally {
ConnectionManager.getConnectionFactory().freeConnection(co);
}
}
/**
* 执行更新、插入语句
* @param sqlStr sql语句
* @return 修改的记录条数
* @throws Exception SQLException
*/
public static int executeUpdate(String sqlStr) {
ConnectionObject co = ConnectionManager.getConnectionFactory().getConnection();
try {
return co.executeUpdate(sqlStr);
}finally {
ConnectionManager.getConnectionFactory().freeConnection(co);
}
}
//web专用
public static List executeQuery(String strSql)
{
if(strSql == null || strSql.trim().length() == 0) return null;
List dbrs = new java.util.ArrayList();
ConnectionObject co = ConnectionManager.getConnectionFactory().getConnection();
try{
ResultSet rs = co.executeQuery(strSql);
try{
ResultSetMetaData rsmd = rs.getMetaData();
int columncount = rsmd.getColumnCount();
while(rs.next()){
String[] tss = new String[columncount];
for(int i=0;i<columncount;i++){
tss[i] = rs.getString(i+1);
}
dbrs.add(tss);
}
}catch(Exception ex){
ex.printStackTrace();
}
}catch(Exception ex){
ex.printStackTrace();
//数据库执行不成功,要向外面的应用抛出异常
} finally{
ConnectionManager.getConnectionFactory().freeConnection(co);
}
return dbrs;
}
}