📄 databasedao.java
字号:
package com.easyjf.dbo;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.ResultSetMetaData;
import java.sql.Statement;
import java.sql.PreparedStatement;
import java.sql.CallableStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import java.util.Collection;
import java.util.Iterator;
/**
* @Title:
* <p>
* 数据库操作工具类
* </p>
* @Description:
* <p>
* 封装了Connection对象,实现对数据库的访问操作
* </p>
* @Copyright:
* <p>
* EasyJF开源团队-EasyDBO项目组
* </p>
* @author:
* <p>
* 动物园的猪
* </p>
* @version:
* <p>
* 2006-4-28第一个板本
* </p>
*
*/
public class DatabaseDAO {
private final static Logger logger = Logger.getLogger(DatabaseDAO.class);
// 属性定义
protected Connection connection;
// 为数据库建立的连接
protected Statement statement;
// 将执行的SQL语句
protected PreparedStatement prepared;
// 将执行的预编译SQL语句
protected CallableStatement callable;
private boolean isAuto = true;
// 默认构造函数
public DatabaseDAO() {
}
/**
* @function:
* <p>
* 构造方法,建立与数据库的连接。
* </p>
* @param-conn:
* <p>
* 对一个数据库的连接对象
* </p>
* @return:
* <p>
* </p>
*/
public DatabaseDAO(Connection conn, boolean isAuto) throws java.sql.SQLException {
connection = conn;
statement = conn.createStatement();// 这一句有点怪怪的,再重新为该对象赋Connection的时候还得初始化一次
this.isAuto = isAuto;
}
/**
* @return 取得连接对象Connection的PreparedStatement对象
*/
public PreparedStatement getPreparedStatement() {
if (prepared != null)
return prepared;
else
return null;
}
public void setPreparedStatement(PreparedStatement ps){
this.prepared = ps;
}
/**
* @function:
* <p>
* 撤销与数据库的连接。
* </p>
* @return:
* <p>
* void
* </p>
*/
public void close() throws java.sql.SQLException {
if(isAuto == true){
if (prepared != null)
prepared.close();
if (callable != null)
callable.close();
if(statement!=null)statement.close();
// if(connection!=null && connection.isClosed() == false)connection.close();
}
}
/**
* 增加一个从外面给这个数据库操作类的设置数据连接的方法
*
* @param connection
*/
public void setConnection(Connection connection) {
this.connection = connection;
try {
if (this.connection != null)
statement = this.connection.createStatement();
} catch (Exception e) {
// 发生错误偶不管了
}
}
/**
* @function:
* <p>
* 获取DAO对象中包含的Connection对象。
* </p>
* @return:
* <p>
* Connection,数据库的连接
* </p>
*/
public Connection getConnection() {
return connection;
}
/**
* @function:
* <p>
* 利用Database的回滚机制进行事务处理。
* </p>
* @return:
* <p>
* void
* </p>
*/
public void rollback() throws java.sql.SQLException {
if (connection != null)
connection.rollback();
}
/**
* @function:
* <p>
* 设置Connection是否自动提交,缺省时是自动提交。
* </p>
* @param-ac:
* <p>
* 设定事务是否每执行一句就自动提交,这时事务是不可回滚的
* </p>
* @return:
* <p>
* void
* </p>
*/
public void setAutoCommit(boolean ac) throws java.sql.SQLException {
if (connection != null)
connection.setAutoCommit(ac);
}
/**
* @function:
* <p>
* 直接已编译好的SQL语句以完成数据库更新操作。
* </p>
* @return:
* <p>
* void
* </p>
*/
public void preparedUpdate() throws java.sql.SQLException {
prepared.executeUpdate();
}
public boolean isPreparedUpdate() throws java.sql.SQLException {
return (prepared.executeUpdate() > 0);
}
public int preparedUpdateNum() throws java.sql.SQLException {
return prepared.executeUpdate();
}
public boolean execute() throws java.sql.SQLException{
return prepared.execute();
}
/**
* Description: 封装设置预编译SQL语句参数的过程。
*/
public void setParameter(int index, boolean value)
throws java.sql.SQLException {
prepared.setBoolean(index, value);
}
public void setParameter(int index, byte value)
throws java.sql.SQLException {
prepared.setByte(index, value);
}
public void setParameter(int index, short value)
throws java.sql.SQLException {
prepared.setShort(index, value);
}
public void setParameter(int index, int value) throws java.sql.SQLException {
prepared.setInt(index, value);
}
public void setParameter(int index, long value)
throws java.sql.SQLException {
prepared.setLong(index, value);
}
public void setParameter(int index, float value)
throws java.sql.SQLException {
prepared.setFloat(index, value);
}
public void setParameter(int index, double value)
throws java.sql.SQLException {
prepared.setDouble(index, value);
}
public void setParameter(int index, byte value[])
throws java.sql.SQLException {
prepared.setBytes(index, value);
}
public void setNull(int a, int b) throws java.sql.SQLException {
prepared.setNull(a, b);
}
public void setNull(int a, int b, String str) throws java.sql.SQLException {
prepared.setNull(a, b, str);
}
/**
* 参JDBCUtil实现 设置prepared的参数
*
* @param index
* column 参数的标号
* @param obj
* Object obj是参数值
* @throws SQLException
*/
public void setParameter(int column, Object obj)
throws java.sql.SQLException {
try {
if (obj instanceof java.lang.String) {
String keyStrs = (String) obj;
prepared.setString(column, keyStrs);
} else if (obj instanceof Integer) {
prepared.setInt(column, ((Integer) obj).intValue());
} else if (obj instanceof Float) {
prepared.setFloat(column, ((Float) obj).floatValue());
} else if (obj instanceof Long) {
prepared.setLong(column, ((Long) obj).longValue());
} else if (obj instanceof Date) {
prepared.setTimestamp(column, new Timestamp(((Date) obj)
.getTime()));
} else if (obj instanceof BigDecimal) {
prepared.setBigDecimal(column, (BigDecimal) obj);
//------Blob,Clob,Binary--------
} else if (obj instanceof Blob){
BlobType blobType = new BlobType();
blobType.set(prepared, obj, column);
} else if (obj instanceof Clob){
ClobType clobType = new ClobType();
clobType.set(prepared, obj, column);
}else //if(obj instanceof Boolean)
{
prepared.setObject(column, obj);
}
//else logger.error("不支持的参数类型!");
} catch (Exception e) {
logger.error("参数设置出错:" + e);
}
}
/**
* 根据参数值queryParams集合
*
* @param queryParams
* @throws Exception
*/
public void setQueryParams(Collection queryParams) throws Exception {
if ((queryParams == null) || (queryParams.isEmpty())) {
return;
}
Iterator iter = queryParams.iterator();
int i = 1;
while (iter.hasNext()) {
Object key = iter.next();
setParameter(i, key);
i++;
}
}
/**
* // 直接以SQL语句查询与更新数据库的方法 Description: 直接执行SQL语句完成数据库查询操作。 Parameters: sql -
* 执行select的SQL语句 Return: 查询结果集 Example: 查询所有用户的sql串可能是"select * from User"
*/
public ResultSet query(String sql) throws java.sql.SQLException {
return statement.executeQuery(sql);
}
/**
* Description: 直接执行SQL语句完成数据库更新操作。 Parameters: sql -
* 执行insert、delete、update等的SQL语句 Example: 插入一个用户的sql串可能是"insert into
* User(id, name) values('lwj','piginzoo')" Note:
* 在sql串中出现的字符串必须用单引号而不可用双引号括住(各处均同)。
*/
public void update(String sql) throws java.sql.SQLException {
statement.executeUpdate(sql);
}
/**
* // 以预编译SQL语句查询与更新数据库的方法 Description: 准备一条预编译的SQL语句。 Parameters: sql -
* 执行查询或更新的SQL语句 Example: 查询所有年龄大于30的用户的sql串可能是"select * from User where age > ?"
*/
public void prepare(String sql) throws java.sql.SQLException {
prepared = connection.prepareStatement(sql);
}
/**
* 以预编译SQL语句查询与更新数据库的方法 Description: 准备一条预编译的SQL语句。
*
* @param sql
* String 执行查询或更新的SQL语句
* @throws SQLException
*/
public void readOnlyPrepare(String sql) throws java.sql.SQLException {
prepared = connection.prepareStatement(sql,
ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
}
/**
* Description: 执行已编译好的SQL语句以完成数据库查询操作。 Return: 查询结果集
*/
public ResultSet preparedQuery() throws java.sql.SQLException {
ResultSet result = prepared.executeQuery();
return result;
}
public void setParameter(int index, String value)
throws java.sql.SQLException {
prepared.setString(index, value);
}
/**
* // 利用存储过程查询与更新数据库的方法 Description: 利用存储过程执行数据库查询操作。 Parameters:
* procedureName - 在数据库中的存储过程名字 Return: 查询结果集
*/
public ResultSet callQuery(String procedureName)
throws java.sql.SQLException {
return callQuery(procedureName,null);
}
/*
public void callUpdate(String procedureName, Object[] parameter) throws java.sql.SQLException {
callable = connection.prepareCall("{call " + procedureName + "}");
callable.executeQuery();
}
*/
/**
* 利用存储过程执行数据库查询操作
*
* @param procedureName
* String 在数据库中的存储过程名字
* @param parameter
* String[]
* @return ResultSet 查询结果集
* @throws SQLException
*/
public ResultSet callQuery(String procedureName, Object[] parameter)
throws java.sql.SQLException {
String strSQL = ""; // SQL语句
// 准备SQL语句
strSQL = "{call " + procedureName;
if ((parameter == null) || (parameter.length == 0)) {
strSQL = strSQL + "}";
} else {
strSQL = strSQL + " (?";
for (int i = 1; i < parameter.length; i++) {
strSQL = strSQL + ",?";
}
strSQL = strSQL + ")}";
}
logger.info(strSQL);
// 准备可调用语句对象
callable = connection.prepareCall(strSQL);
// 设置输入参数
if ((parameter != null) && (parameter.length >= 1)) {
for (int i = 1; i <= parameter.length; i++) {
callable.setObject(i, parameter[i - 1]);
logger.info("输入参数:" + parameter[i - 1]);
}
}
ResultSet result = callable.executeQuery();
return result;
}
/**
* ResultSet结果集rs转换成List集合
*
* @param rs
* ResultSet 待转换的ResultSet
* @return List
* @throws Exception
*/
public List resultSet2List(ResultSet rs) throws Exception {
if (rs == null) {
return null;
}
List ret = new ArrayList();
while (rs.next()) {
ret.add(resultSet2Map(rs));
}
return ret;
}
/**
* 把java.sql.ResultSet结果集rs转换成Map集合
*
* @param rs
* ResultSet 待转换的ResultSet
* @return Map
* @throws Exception
*/
public Map resultSet2Map(ResultSet rs) throws Exception {
if (rs == null) {
return null;
}
ResultSetMetaData meta = rs.getMetaData();
int count = meta.getColumnCount();
Map map = new HashMap(count);
for (int i = 1; i <= count; i++) {
logger.debug("加载字段"+meta.getColumnName(i));
map.put(meta.getColumnName(i),rs.getObject(i));
}
return map;
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -