📄 dbutil.java
字号:
package com.work.db;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Vector;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DbUtil {
private static Log log = LogFactory.getLog(DbUtil.class);
/**
* 如果执行成功,那么就返回影响的记录数目。否则返回0;<br />
* 注意:如果是多条sql语句用分号“;”分割,那么它返回的影响记录的数目就不准了。所以只用来执行单条sql语句。<br>
* sqlserver2000返回的是第一条sql语句影响的记录数。<br>
* @param sql 不能为空,可以是insert、update、delete语句;
* @return int
*/
public static int executeUpdate(String sql) {
int result = 0;
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是insert、update或者delete语句。");
return 0;
}
Connection conn = null;
PreparedStatement pst = null;
try {
conn = DbConnection.getConn();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
result = pst.executeUpdate();
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
log.info("数据库会滚失败!", e);
}
log.error(sql + "语句执行失败!请仔细检查!", e);
result = 0;
} finally {
try {
if (pst != null)
pst.close();
} catch (SQLException e) {
log.info("关闭PreparedStatement失败!", e);
}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
log.info("关闭数据库连接失败!", e);
}
}
return result;
}
/**
* 可以用来执行任意的sql语句。
*
* @param sql
* @return 返回true if the first result is a ResultSet object; false if the
* first result is an update count or there is no result
*
* @throws SQLException
* 抛出异常说明执行失败!否则执行成功!
*/
private static void execute(String sql) throws SQLException {
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空。");
return;
}
Connection conn = null;
PreparedStatement pst = null;
try {
conn = DbConnection.getConn();
conn.setAutoCommit(false);
pst = conn.prepareStatement(sql);
pst.execute();
conn.commit();
} catch (SQLException e) {
try {
conn.rollback();
} catch (SQLException e1) {
log.info("数据库会滚失败!", e);
}
log.error(sql + "语句执行失败!请仔细检查!", e);
throw new SQLException("执行失败!");
} finally {
try {
if (pst != null)
pst.close();
} catch (SQLException e) {
log.info("关闭PreparedStatement失败!", e);
}
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
log.info("关闭数据库连接失败!", e);
}
}
}
/**
* 关闭ResultSet对象
* @param rst
*/
public static void closeResultSet(ResultSet rst) {
try {
if (rst != null)
rst.close();
} catch (SQLException e) {
log.error("关闭ResultSet出错!", e);
}
}
/**
* 关闭Statement对象。
* @param stmt
*/
public static void closeStatement(Statement stmt) {
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {
log.error("关闭Statement出错!", e);
}
}
/**
* 关闭PreparedStatement对象
* @param pst
*/
public static void closeStatement(PreparedStatement pst) {
try {
if (pst != null)
pst.close();
} catch (SQLException e) {
log.error("关闭PreparedStatement出错!", e);
}
}
/**
* 关闭Connection
* @param conn
*/
public static void closeConnection(Connection conn) {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
log.error("关闭数据库连接出错!", e);
}
}
/**
* 同时关闭Statement和Connection
* @param stmt
* @param conn
*/
public static void closeStatementAndConnection(Statement stmt,
Connection conn) {
closeStatement(stmt);
closeConnection(conn);
}
/**
* 同时关闭PreparedStatement和Connection
* @param pst
* @param conn
*/
public static void closeStatementAndConnection(PreparedStatement pst,
Connection conn) {
closeStatement(pst);
closeConnection(conn);
}
/**
* 同时关闭ResultSet、 Statement 、Connection
* @param rst
* @param stmt
* @param conn
*/
public static void closeAll(ResultSet rst, Statement stmt, Connection conn) {
closeResultSet(rst);
closeStatement(stmt);
closeConnection(conn);
}
/**
* 同时关闭ResultSet、 PreparedStatement 、Connection
* @param rst
* @param pst
* @param conn
*/
public static void closeAll(ResultSet rst, PreparedStatement pst,
Connection conn) {
closeResultSet(rst);
closeStatement(pst);
closeConnection(conn);
}
/**
* 返回结果集Vector。线程安全的。Vector中包含的是HashTable。HashTable的key就sql语句中的字段名的小写。
*
* @param sql
* @return Vector,返回的结果要么为null,要么至少包含一条查询记录;
* @throws SQLException
*/
public static Vector executeQueryVector(String sql) {
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是select语句。");
throw new NullPointerException("sql参数不能为空字符串或者null。");
}
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
Vector v = new Vector();
try {
conn = DbConnection.getConn();
pst = conn.prepareStatement(sql);
ResultSetMetaData rsmd = pst.getMetaData();
int columnCount = rsmd.getColumnCount();//获取所有的列数;
String[] columnStr = new String[columnCount];
for(int i=1;i<=columnCount;i++){
columnStr[i-1]=rsmd.getColumnName(i).toLowerCase();//都转换为小写
}
rst = pst.executeQuery();
while(rst.next()){
Hashtable hash = new Hashtable();
for(int i=0;i<columnCount;i++){
hash.put(columnStr[i],rst.getObject(columnStr[i])==null?"":rst.getObject(columnStr[i])); //如果key和value任意一个为null,均会抛出异常
}
v.add(hash);
}
if(v.size()<1)
v = null;
} catch (SQLException e) {
log.error(sql+"语句查询出错!",e);
return null;
}finally{
closeAll(rst,pst,conn);
}
return v;
}
/**
* 返回结果集List。 list中包含的是hashmap。hashMap的key就sql语句中的字段名的小写。
*
* @param sql
* @return list,返回的结果list要么为null,要么包含数据;
* @throws SQLException
*/
public static List executeQueryList(String sql) {
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是select语句。");
throw new NullPointerException("sql参数不能为空字符串或者null。");
}
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
List l = new ArrayList();
try {
conn = DbConnection.getConn();
pst = conn.prepareStatement(sql);
ResultSetMetaData rsmd = pst.getMetaData();
int columnCount = rsmd.getColumnCount();//获取所有的列数;
String[] columnStr = new String[columnCount];
for(int i=1;i<=columnCount;i++){
columnStr[i-1]=rsmd.getColumnName(i).toLowerCase();//都转换为小写
}
rst = pst.executeQuery();
while(rst.next()){
HashMap map = new HashMap();
for(int i=0;i<columnCount;i++){
map.put(columnStr[i],rst.getObject(columnStr[i])==null?"":rst.getObject(columnStr[i])); //如果key和value任意一个为null,均会抛出异常
}
l.add(map);
}
if(l.size()<1)
l = null;
} catch (SQLException e) {
log.error(sql+"语句查询出错!",e);
return null;
}finally{
closeAll(rst,pst,conn);
}
return l;
}
/**
* 返回结果集List。 list中包含的是String【】数组。 她不像List中包含HashMap,直接保存的就是结果没有key。
*
* @param sql
* @return list,返回的结果list要么为null,要么包含数据;
* @throws SQLException
*/
public static List executeQueryStringList(String sql) {
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是select语句。");
throw new NullPointerException("sql参数不能为空字符串或者null。");
}
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
List l = new ArrayList();
try {
conn = DbConnection.getConn();
pst = conn.prepareStatement(sql);
ResultSetMetaData rsmd = pst.getMetaData();
int columnCount = rsmd.getColumnCount();//获取所有的列数;
String[] columnStr = new String[columnCount];
for(int i=1;i<=columnCount;i++){
columnStr[i-1]=rsmd.getColumnName(i).toLowerCase();//都转换为小写
}
rst = pst.executeQuery();
//Object[] tempObject = null;
rst = pst.executeQuery();
while(rst.next()){
String[] tempObject = new String[columnCount];
for(int i=0;i<columnCount;i++){
tempObject[i]=rst.getObject(columnStr[i])==null?"":rst.getObject(columnStr[i]).toString(); //如果key和value任意一个为null,均会抛出异常
}
l.add(tempObject);
}
if(l.size()<1)
l = null;
} catch (SQLException e) {
log.error(sql+"语句查询出错!",e);
return null;
}finally{
closeAll(rst,pst,conn);
}
return l;
}
/**
* 传入的sql语句只能够是count(*) 或者sum(字段)或者max(字段),只能够查询整数的sql。
* @param sql
* @return 返回一个数字。0或者比0大的整数。
*/
public static int getCount(String sql){
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是select语句。");
throw new NullPointerException("sql参数不能为空字符串或者null。");
}
int result = 0;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
try {
conn = DbConnection.getConn();
pst = conn.prepareStatement(sql);
rst = pst.executeQuery();
while(rst.next()){
result = rst.getInt(1);
}
} catch (SQLException e) {
log.error(sql+"语句查询出错!",e);
return 0;
}finally{
closeAll(rst,pst,conn);
}
return result;
}
/**
* 传入的sql语句只能够获取一个字符串结果的sql,第一个字段必须是String类型,其他的会被忽略。<br>
* 此方法只能用于返回要查询的结果既不为null也不是空字符串的情况。
* @param sql
* @return 要么返回null,要么返回一个不是空字符串的结果。
*/
public static String getStringResult(String sql){
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是select语句。");
throw new NullPointerException("sql参数不能为空字符串或者null。");
}
String result = "";
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
try {
conn = DbConnection.getConn();
pst = conn.prepareStatement(sql);
rst = pst.executeQuery();
while(rst.next()){
result = rst.getString(1);
}
} catch (SQLException e) {
log.error(sql+"语句查询出错!",e);
return null;
}finally{
closeAll(rst,pst,conn);
}
if("".equals(result)) result = null;
return result;
}
/**
* 传入的sql语句只能够是count(*) 或者sum(字段)或者max(字段),只能够查询整数的sql。
* @param sql
* @return 返回一个float类型的数字
*/
public static float getFloatCount(String sql){
if (sql == null || sql.trim().equals("")) {
log.info("参数sql不能为空,必须是select语句。");
throw new NullPointerException("sql参数不能为空字符串或者null。");
}
float result = 0.0f;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
try {
conn = DbConnection.getConn();
pst = conn.prepareStatement(sql);
rst = pst.executeQuery();
while(rst.next()){
result = rst.getFloat(1);
}
} catch (SQLException e) {
log.error(sql+"语句查询出错!",e);
return 0;
}finally{
closeAll(rst,pst,conn);
}
return result;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -