一、jdbc 数据库连接 例子
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import jp.co.ntt.oims.eif.statusbat.exception.DatabaseException;
import jp.co.ntt.oims.eif.statusbat.exception.SystemException;
public final class DBManager {
/** DB接続ユーザ名設定キー */
public static final String SETTING_DB_USER = "JDBC_CONNECT_USER";
/** DB接続ユーザのパスワード設定キー */
public static final String SETTING_DB_PASS = "JDBC_CONNECT_PWD";
/** DB接続インスタンス名設定キー */
public static final String SETTING_DB_SID = "JDBC_CONNECT_URL";
/**
* コンストラクタ<BR>
*/
private DBManager() {
}
/**
* DB接続をテストする。<br>
* @throws DatabaseException DB接続異常の場合
*/
public static void testDB() throws DatabaseException {
Connection conn = getConnection();
closeConnection(conn);
}
/**
* 常駐するDBコネクションを取得する。<br>
* 常駐するDBコネクションがない場合、DBに接続し、コネクションを返す。
* @return Connection DBコネクション
* @throws DatabaseException DB接続異常の場合
*/
public static Connection getConnection() throws DatabaseException {
return getRealConnection();
}
/**
* 使用したDBコネクションを返す。<br>
* @param conn DBコネクション
* @throws DatabaseException DBコネクションクローズ失敗の場合
*/
public static void closeConnection(Connection conn)
throws DatabaseException {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
}
}
/**
* リアルDBコネクションを取得する。<br>
* @return Connection リアルDBコネクション
* @throws DatabaseException DBコネクション取得失敗の場合
*/
private static Connection getRealConnection() throws DatabaseException {
String url = Setting.getInstance().getValue(SETTING_DB_SID);
String username = Setting.getInstance().getValue(SETTING_DB_USER);
String password = Setting.getInstance().getValue(SETTING_DB_PASS);
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
return DriverManager.getConnection(url, username, password);
} catch (ClassNotFoundException e) {
throw new SystemException(e.getMessage(), e);
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
}
}
}
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import jp.co.ntt.oims.eif.statusbat.common.Log;
import jp.co.ntt.oims.eif.statusbat.exception.DatabaseException;
public abstract class AbstractBaseDAO {
/** DBコネクション */
protected Connection conn;
/** ロガー */
protected Log logger;
/**
* コンストラクタ<BR>
* @param conn DBコネクション
*/
public AbstractBaseDAO(Connection conn) {
if (null == conn) {
throw new NullPointerException();
}
this.conn = conn;
this.logger = Log.getInstance(this.getClass());
}
/**
* テーブルのデータ取得処理を行う。<BR>
* <BR>
* 引数のSQL文、SQLパラメータより、テーブルのデータ取得処理を行う。<BR>
* @param strSQL SQL文
* @param paraList SQLパラメータ
* @return 取得されたデータ
* @throws DatabaseException DB異常の場合
*/
protected List<Map<Integer, String>> doSelect(String strSQL,
List<Object> paraList) throws DatabaseException {
ResultSet resultSet = null;
List<Map<Integer, String>> dataList = new ArrayList<Map<Integer, String>>();
try {
resultSet = executeQuery(strSQL, paraList);
int iMaxColumn = 0;
ResultSetMetaData metaData = resultSet.getMetaData();
iMaxColumn = metaData.getColumnCount();
while (resultSet.next()) {
Map<Integer, String> dataMap = new HashMap<Integer, String>();
for (int i = 0; i < iMaxColumn; i++) {
dataMap.put(i, resultSet.getString(i + 1));
}
dataList.add(dataMap);
}
return dataList;
} catch (SQLException se) {
throw new DatabaseException(se.getMessage(), se);
} catch (DatabaseException dbe) {
throw dbe;
} finally {
if (null != resultSet) {
try {
resultSet.getStatement().close();
} catch (SQLException se) {
logger.debug(se.getMessage());
}
}
}
}
/**
* SQL文(DML)を実行。
* @param strSQL SQL文(DML)
* @param paraList SQL文のパラメータリスト
* @return 更新の行数
* @throws DatabaseException DBアクセス異常
*/
protected int executeUpdate(String strSQL, List<Object> paraList)
throws DatabaseException {
logger.debug(strSQL);
if (paraList != null) {
logger.debug("PARAM : " + paraList.toString());
}
PreparedStatement st = getPreparedStatement(strSQL);
st = setParameter(st, paraList);
try {
return st.executeUpdate();
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
} finally {
try {
st.close();
} catch (SQLException e) {
logger.debug(e.getMessage());
}
}
}
/**
* SQLクエリを実行。
* @param strSQL SQL文
* @param paraList SQL文のパラメータリスト
* @return ResultSet SQLクエリ結果
* @throws DatabaseException DBアクセス異常
*/
private ResultSet executeQuery(String strSQL, List<Object> paraList)
throws DatabaseException {
logger.debug(strSQL);
if (paraList != null) {
logger.debug("PARAM : " + paraList.toString());
}
PreparedStatement st = getPreparedStatement(strSQL);
st = this.setParameter(st, paraList);
try {
ResultSet rs = st.executeQuery();
return rs;
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
}
}
/**
* PreparedStatementを返す。
* @param strSQL SQL文
* @return PreparedStatement PreparedStatementオブジェクト
* @throws DatabaseException DBアクセス異常
*/
private PreparedStatement getPreparedStatement(String strSQL)
throws DatabaseException {
PreparedStatement result = null;
try {
result = conn.prepareStatement(strSQL);
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
}
return result;
}
/**
* PreparedStatementにSQLのパラメータを設定。
* @param st PreparedStatement
* @param paraList SQL文のパラメータリスト
* @return PreparedStatement パラメータ設定済みPreparedStatement
* @throws DatabaseException DBアクセス異常
*/
private PreparedStatement setParameter(PreparedStatement st,
List<Object> paraList) throws DatabaseException {
try {
if (paraList != null) {
for (int i = 0; i < paraList.size(); i++) {
Object curPara = paraList.get(i);
if (curPara instanceof String) {
st.setString(i + 1, (String) curPara);
} else if (curPara instanceof Date) {
st.setTimestamp(i + 1, new Timestamp(((Date) curPara)
.getTime()));
} else {
st.setObject(i + 1, curPara);
}
}
}
return st;
} catch (SQLException e) {
throw new DatabaseException(e.getMessage(), e);
}
}
}
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import jp.co.ntt.oims.eif.statusbat.common.Log;
import jp.co.ntt.oims.eif.statusbat.exception.DatabaseException;
public final class AlarmStatusDao extends AbstractBaseDAO {
/** ログ */
private static Log logger = Log.getInstance(AlarmStatusDao.class);
/** SQL1 */
private static final String SQL_SEL_ALM = "SELECT DISTINCT T.リクエストid \n"
+ " FROM ARADMIN.\"OIMS_VIEW_工事対象_新フィルタ\" T\n"
+ " WHERE T.CONST_SYS_REQID = ? \n"
+ " AND ((T.AF_STATUS_CD = ? AND\n"
+ " TO_DATE(T.LAST_SET_FILTER_END_DT, 'YYYY.MM.DD.HH24.MI.SS') <= SYSDATE)\n"
+ " OR T.AF_STATUS_CD = ? )";
/** SQL2 */
private static final String SQL_UPD_ALM = "UPDATE T_ALARM_FILTER_STATUS T "
+ "SET T.AF_STATUS_CD = ? " + "WHERE T.REMEDY_REQ_ID = ?";
/** SQL3 */
private static final String SQL_SEL_CONST = "SELECT DISTINCT O.SYS_リクエストID\n"
+ " FROM ARADMIN.\"OIMS_工事通報書画面\" O\n"
+ " LEFT JOIN ARADMIN.\"OIMS_VIEW_工事対象_新フィルタ\" OV\n"
+ " ON O.SYS_リクエストID = OV.CONST_SYS_REQID\n"
+ "WHERE 1=1\n"
+ " AND O.\"基本情報_ステータス\" = ? \n"
+ " AND ((\n"
+ " (O.\"基本情報_サービス影響\" in(?,?) )\n"
+ " AND\n"
+ " TO_DATE(TO_CHAR(TO_DATE(19700101090000 , 'YYYYMMDDHH24MISS')+(O.\"基本情報_工事終了日時計画\" / 24 / 60 / 60) , 'YYYYMMDDHH24MISS') , 'YYYYMMDDHH24MISS') <= SYSDATE\n"
+ " )OR(\n"
+ " ((O.\"基本情報_サービス影響\" IS NULL OR O.\"基本情報_サービス影響\" not in(?,?)) )\n"
+ " AND\n"
+ " TO_DATE(TO_CHAR(TO_DATE(19700101090000 , 'YYYYMMDDHH24MISS')+(O.\"サービスT_工事終了日時\" / 24 / 60 / 60) , 'YYYYMMDDHH24MISS') , 'YYYYMMDDHH24MISS') <= SYSDATE\n"
+ " ))\n"
+ " AND NOT EXISTS(\n"
+ " SELECT OV1.CONST_SYS_REQID FROM ARADMIN.\"OIMS_VIEW_工事対象_新フィルタ\" OV1\n"
+ " WHERE 1= 1\n"
+ " AND OV1.CONST_SYS_REQID = OV.CONST_SYS_REQID\n"
+ " AND OV1.AF_STATUS_CD =? \n"
+ " AND TO_DATE(OV1.LAST_SET_FILTER_END_DT,'YYYY.MM.DD.HH24:MISS') > SYSDATE\n"
+ " )";
/**
* コンストラクタ<BR>
* @param conn DBコネクション
*/
private AlarmStatusDao(Connection conn) {
super(conn);
}
/**
* インスタンスを取得する
* @param conn DBコネクション
* @return AlarmStatusDao アラームステータスDAO処理インスタンス
*/
public static AlarmStatusDao getInstance(Connection conn) {
return new AlarmStatusDao(conn);
}
/**
* アラームフィルタステータスを「解除済み」に更新する。<br>
* 引数の工事通報書リクエストIDに対して、アラームフィルタステータスが”設定済”かつ、<br>
* フィルタ終了時刻≦現在時刻、または”中断中”の工事対象が存在する場合、<br>
* アラームフィルタステータスを「解除済み」に更新する。<br>
* @param requestID 工事通報書のリクエストID
* @throws DatabaseException DB操作異常の場合
*/
public void updateDBAlarmStatus(String requestID) throws DatabaseException {
List<Object> paramList = new ArrayList<Object>();
paramList.add(requestID);
paramList.add("設定済");
paramList.add("中断中");
List<Map<Integer, String>> list;
list = super.doSelect(SQL_SEL_ALM, paramList);
if (!list.isEmpty()) {
for (Map<Integer, String> map : list) {
paramList = new ArrayList<Object>();
String objId = map.get(0);
paramList.add("04");
paramList.add(objId);
logger.log("EIF-STBAT-030006", new String[]{SQL_UPD_ALM});
super.executeUpdate(SQL_UPD_ALM, paramList);
logger.log("EIF-STBAT-030004", new String[]{requestID, objId});
}
} else {
logger.log("EIF-STBAT-030005", new String[]{requestID});
}
}
/**
* 完了済みの工事通報書のリクエストIDを取得する。<br>
* 工事通報書のステータスが「工事中」且つ、 サービス影響終了日時(サービス影響が”無”or”調査中”の場合は工事終了日時)が<br>
* 経過している(≦現在時刻)、且つアラームフィルタステータスが”設定済”でフィルタ終了時刻>現在時刻のレコードが存在しないの<br>
* 工事通報書画面のRemedyリクエストIDを取得する。<br>
* @return 工事通報書のリクエストID配列
* @throws DatabaseException DB操作異常の場合
*/
public List<String> getDBFinishedConst() throws DatabaseException {
List<Object> paramList = new ArrayList<Object>();
paramList.add("工事中");
paramList.add("1");
paramList.add("2");
paramList.add("1");
paramList.add("2");
paramList.add("設定済");
List<String> rList = new ArrayList<String>();
List<Map<Integer, String>> list;
list = super.doSelect(SQL_SEL_CONST, paramList);
if (list != null && !list.isEmpty()) {
for (Map<Integer, String> map : list) {
rList.add(map.get(0));
}
}
return rList;
}
}
------------------------------------------------------------------------------------------------------------------------------------
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.Writer;
import java.math.BigDecimal;
import java.sql.Blob;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Time;
import java.sql.Timestamp;
import java.sql.Types;
import java.text.DateFormat;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import oracle.sql.BLOB;
import oracle.sql.CLOB;
import com.sysoft.baseform.process.util.LogProxy;
import com.sysoft.baseform.process.util.StringUtil;
public class JdbcManager {
private static DataSourceFactory dsf;
private String msg = "";
private int effRow;
public JdbcManager() {
dsf = DataSourceFactory.create();
}
public JdbcManager(String otherJndiName) {
dsf = DataSourceFactory.create(otherJndiName);
}
/**
* 获取出错信息内容
* @return String 出错信息字符串
*/
public String getMessage() {
if (msg != null) {
String tempMsg = replaceString(msg, "\n", "");
tempMsg = replaceString(tempMsg, "\r", "");
if (tempMsg.trim().equals("")) {
return null;
}
}
return msg;
}
/**
* 对HTML代码进行解码
*/
public String htmlDecoding(String encodedHtml) {
String result = encodedHtml;
result = replaceString(result, "<", "<");
result = replaceString(result, ">", ">");
return result;
}
/**
* 对HTML代码进行编码
*/
public String htmlEncoding(String strHtml) {
String result = strHtml;
result = replaceString(result, "<", "<");
result = replaceString(result, ">", ">");
return result;
}
/**
* 处理Sql语句中的特殊字符,如"'"必须替换成"''"
*/
public String disposeSqlValue(String sqlValue) {
if (sqlValue == null || sqlValue.trim().equals("")) {
return "";
}
sqlValue = replaceString(sqlValue.trim(), "'", "''");
return sqlValue;
}
/**
* 执行删除操作
* @param deleteSql 要执行的sql语句
* @return 执行成功返回true,否则返回false
*/
public boolean executeDelete(String deleteSql) {
deleteSql = StringUtil.insertIntoDB(deleteSql);
return execute(deleteSql);
}
/**
* 执行插入操作
* @param insertSql 要执行的sql语句
* @return 执行成功返回true,否则返回false
*/
public boolean executeInsert(String insertSql) {
insertSql = StringUtil.insertIntoDB(insertSql);
return execute(insertSql);
}
public Connection getConnection(){
if(dsf == null)
return null;
return dsf.getConnection();
}
/**
* 多条语句插入、修改的事务处理
* @param sqls
* @return
*/
public boolean executeTrans(List sqls){
if(sqls == null || sqls.isEmpty())
return false;
if (dsf == null) {
dsf = DataSourceFactory.create();
}
if (dsf == null) {
setMessage("对不起,创建数据源工厂对象失败。");
return false;
}
Connection conn = dsf.getConnection();
if (conn == null) {
setMessage("对不起,无法获取数据库连接。");
return false;
}
Statement stmt = null;
String sql = "";
try {
long first = System.currentTimeMillis();
conn.setAutoCommit(false);
stmt = conn.createStatement();
for(int i=0;i<sqls.size();i++){
Object o = sqls.get(i);
if( List.class.isInstance(o)){
List temp = (List)o;
for(int m =0;m<temp.size();m++){
sql = (String)temp.get(m);
stmt.addBatch(StringUtil.insertIntoDB(sql));
}
}else if(StringBuffer.class.isInstance(o)){
sql = ((StringBuffer)o).toString();
stmt.addBatch(StringUtil.insertIntoDB(sql));
}else{
sql = (String)o;
stmt.addBatch(StringUtil.insertIntoDB(sql));
}
}
stmt.executeBatch();
conn.commit();
LogProxy.debug("The insert tran time is :"+(System.currentTimeMillis()-first));
conn.setAutoCommit(true);
return true;
}
catch (SQLException e) {
try{
conn.rollback();
conn.setAutoCommit(true);
}catch(SQLException ex){
System.out.println("call back error:"+ex.getMessage());
}
System.out.println("sql error:" + e.getMessage());
System.out.println("the error sql is:" + sql);
setMessage("对不起,数据库更新失败:" + e.getMessage());
return false;
}
finally {
try {
if (stmt != null) {
stmt.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.setAutoCommit(true);
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
/**
* 向指定表中插入一条记录数据
* @param tableName 表名
* @param data 存放记录数据的Hashtable对象<br>
* BLOB类型或BINARY类型的字段要求com.jspsmart.upload.File对象<br>
* 其他类型的字段要求String对象
* @return 若插入成功返回true,否则返回false
*/
public boolean executeInsert(String tableName, Hashtable data) {
Connection conn = DataSourceFactory.create().getConnection();
if (conn == null) {
setMessage("对不起,获取数据库连接时出现错误!");
return false;
}
Hashtable newData = toUperCaseHashtable(data);
StringBuffer metaSql = new StringBuffer("select "); //用于获取表结构的Sql语句
StringBuffer sql = new StringBuffer("insert into "); //用于插入数据的Sql语句
sql.append(tableName);
sql.append(" (");
StringBuffer sbval = new StringBuffer(") values (");
Enumeration items = newData.keys();
String item;
while (items.hasMoreElements()) {
item = items.nextElement().toString();
sql.append(item);
sql.append(",");
sbval.append("?,");
metaSql.append(item);
metaSql.append(",");
}
if (sql.charAt(sql.length() - 1) == ',')
sql.deleteCharAt(sql.length() - 1);
if (sbval.charAt(sbval.length() - 1) == ',')
sbval.deleteCharAt(sbval.length() - 1);
if (metaSql.charAt(metaSql.length() - 1) == ',')
metaSql.deleteCharAt(metaSql.length() - 1);
sql.append(sbval.toString());
sql.append(")");
metaSql.append(" from ");
metaSql.append(tableName);
metaSql.append(" where rownum <= 1");
PreparedStatement pre = null; //用于插入数据的PreparedStatement对象
PreparedStatement preMeta = null; //用于获取表结构的PreparedStatement对象
ResultSetMetaData rsmd = null;
ResultSet rs = null; //用于获取表结构的ResultSet对象
try {
conn.setAutoCommit(false);
preMeta = conn.prepareStatement(metaSql.toString());
rs = preMeta.executeQuery();
rsmd = rs.getMetaData();
pre = conn.prepareStatement(sql.toString());
Object columnValue;
String columnName;
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
columnName = rsmd.getColumnName(i).toUpperCase();
//columnValue = newData.get(columnName);
if(newData.get(columnName) instanceof String)
columnValue = StringUtil.insertIntoDB((String)newData.get(columnName));
else
columnValue = newData.get(columnName);
if (columnValue != null) {
pre = setColumnValue(conn, pre, i, rsmd.getColumnType(i), columnValue);
}
}
pre.execute();
conn.commit();
return true;
}
catch (ParseException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("数据转换错误:" + e.getMessage());
setMessage("对不起,数据转换时发生错误!\\n" + e.getMessage());
return false;
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("插入记录错误:" + e.getMessage());
System.out.println("错误的SQL语句为: " + sql.toString());
setMessage("对不起,插入记录发生错误!\\n" + e.getMessage());
return false;
}
catch (IOException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("文件数据读取错误:" + e.getMessage());
setMessage("对不起,文件数据读取发生错误!\\n" + e.getMessage());
return false;
}
catch (Exception e) {
try {
conn.rollback();
}
catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("未知错误:" + e.getMessage());
System.out.println("错误时的SQL语句为: " + sql.toString());
setMessage("对不起,发生未知错误!\\n" + e.getMessage());
e.printStackTrace();
return false;
}
finally {
try {
if (preMeta != null) {
preMeta.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (pre != null) {
pre.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.setAutoCommit(true);
}
}
catch (SQLException e) {
System.out.println("恢复Connection对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
//随便处理了个带事物处理的
public boolean executeInsertWithTrans(Connection conn,String tableName, Hashtable data) {
Hashtable newData = toUperCaseHashtable(data);
StringBuffer metaSql = new StringBuffer("select "); //用于获取表结构的Sql语句
StringBuffer sql = new StringBuffer("insert into "); //用于插入数据的Sql语句
sql.append(tableName);
sql.append(" (");
StringBuffer sbval = new StringBuffer(") values (");
Enumeration items = newData.keys();
String item;
while (items.hasMoreElements()) {
item = items.nextElement().toString();
sql.append(item);
sql.append(",");
sbval.append("?,");
metaSql.append(item);
metaSql.append(",");
}
if (sql.charAt(sql.length() - 1) == ',')
sql.deleteCharAt(sql.length() - 1);
if (sbval.charAt(sbval.length() - 1) == ',')
sbval.deleteCharAt(sbval.length() - 1);
if (metaSql.charAt(metaSql.length() - 1) == ',')
metaSql.deleteCharAt(metaSql.length() - 1);
sql.append(sbval.toString());
sql.append(")");
metaSql.append(" from ");
metaSql.append(tableName);
metaSql.append(" where rownum <= 1");
PreparedStatement pre = null; //用于插入数据的PreparedStatement对象
PreparedStatement preMeta = null; //用于获取表结构的PreparedStatement对象
ResultSetMetaData rsmd = null;
ResultSet rs = null; //用于获取表结构的ResultSet对象
Object columnValue = null;
String columnName = "";
try {
conn.setAutoCommit(false);
preMeta = conn.prepareStatement(metaSql.toString());
rs = preMeta.executeQuery();
rsmd = rs.getMetaData();
pre = conn.prepareStatement(sql.toString());
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
columnName = rsmd.getColumnName(i).toUpperCase();
//columnValue = newData.get(columnName);
if(newData.get(columnName) instanceof String)
columnValue = StringUtil.insertIntoDB((String)newData.get(columnName));
else
columnValue = newData.get(columnName);
System.out.println(tableName+"的字段-["+columnName+"]--类型为:"+rsmd.getColumnType(i));
if (columnValue != null) {
pre = setColumnValue(conn, pre, i, rsmd.getColumnType(i), columnValue);
}
}
pre.execute();
return true;
}
catch (Exception e) {
e.printStackTrace();
System.out.println("插入错误" + e.getMessage()+"\n错误的字段:"+columnName);
System.out.println("Error数据:"+data);
return false;
}
finally {
try {
if (preMeta != null) {
preMeta.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (pre != null) {
pre.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
}
}
/**
* 执行更新操作
* @param updateSql 要执行的sql语句
* @return 执行成功返回true,否则返回false
*/
public boolean executeUpdate(String updateSql) {
updateSql = StringUtil.insertIntoDB(updateSql);
return execute(updateSql);
}
/**
* 在指定表中更新指定记录的数据
* @param tableName 表名
* @param data 存放记录数据的Hashtable对象<br>
* BLOB类型或BINARY类型的字段要求com.jspsmart.upload.File对象<br>
* 其他类型的字段要求String对象
* @param condition 条件字符串,用于确定更新记录
* @return 若更新成功返回true,否则返回false
*/
public boolean executeUpdate(String tableName, Hashtable data, String condition) {
Connection conn = DataSourceFactory.create().getConnection();
if (conn == null) {
setMessage("对不起,获取数据库连接时出现错误!");
return false;
}
Hashtable newData = toUperCaseHashtable(data);
StringBuffer metaSql = new StringBuffer("select "); //用于获取表结构的Sql语句
StringBuffer sql = new StringBuffer("update ");
sql.append(tableName);
sql.append(" set ");
Enumeration items = newData.keys();
String item;
while (items.hasMoreElements()) {
item = items.nextElement().toString();
sql.append(item);
sql.append("=?,");
metaSql.append(item);
metaSql.append(",");
}
if (sql.charAt(sql.length() - 1) == ',')
sql.deleteCharAt(sql.length() - 1);
if (metaSql.charAt(metaSql.length() - 1) == ',')
metaSql.deleteCharAt(metaSql.length() - 1);
sql.append(" where ");
sql.append(condition);
metaSql.append(" from ");
metaSql.append(tableName);
metaSql.append(" where rownum <= 1");
PreparedStatement pre = null;
PreparedStatement preMeta = null; //用于获取表结构的PreparedStatement对象
ResultSetMetaData rsmd = null; //用于获取表结构的ResultSetMetaData对象
ResultSet rs = null; //用于获取表结构的ResultSet对象
try {
conn.setAutoCommit(false);
preMeta = conn.prepareStatement(metaSql.toString());
rs = preMeta.executeQuery();
rsmd = rs.getMetaData();
pre = conn.prepareStatement(sql.toString());
Object columnValue;
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
String columnName = rsmd.getColumnName(i).toUpperCase();
if(newData.get(columnName) instanceof String)
columnValue = StringUtil.insertIntoDB((String)newData.get(columnName));
else
columnValue = newData.get(columnName);
pre = setColumnValue(conn, pre, i, rsmd.getColumnType(i), columnValue);
}
pre.execute();
conn.commit();
effRow=pre.getUpdateCount();
return true;
}
catch (ParseException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("数据转换错误:" + e.getMessage());
setMessage("数据转换错误:" + e.getMessage());
return false;
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("插入记录错误:" + e.getMessage());
System.out.println("错误的SQL语句为: " + sql.toString());
System.out.print("错误时的插入数据为:" + newData);
setMessage("插入记录错误:" + e.getMessage());
return false;
}
catch (IOException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("文件数据读取错误:" + e.getMessage());
setMessage("文件数据读取错误:" + e.getMessage());
return false;
}
catch (Exception e) {
try {
conn.rollback();
}
catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("未知错误:" + e.getMessage());
System.out.println("错误时的SQL语句为: " + sql.toString());
System.out.print("错误时的插入数据为:" + newData);
setMessage("对不起,发生未知错误!\\n" + e.getMessage());
return false;
}
finally {
try {
if (preMeta != null) {
preMeta.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (pre != null) {
pre.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.setAutoCommit(true);
}
}
catch (SQLException e) {
System.out.println("恢复Connection对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
public boolean execute(Connection conn, String sql, MetaDataEx[] datas) {
if (conn!=null) {
PreparedStatement pre = null;
try {
pre = conn.prepareStatement(sql);
if (datas != null&& datas.length > 0)
{
for (int i = 0; i < datas.length; i++) {
try {
Object obj= datas[i].getValue();
Object columnValue = null;
if(obj instanceof String)
columnValue = StringUtil.insertIntoDB((String)obj);
else
columnValue = obj;
pre = setColumnValue(conn, pre, i + 1, datas[i].getType(),
columnValue);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
}
}
pre.execute();
return true;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return false;
}
finally {
try {
if (pre != null) {
pre.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
}
}
return false;
}
public boolean execute(String sql, MetaDataEx[] datas) {
Connection conn = DataSourceFactory.create().getConnection();
if (conn == null) {
setMessage("对不起,获取数据库连接时出现错误!");
return false;
}
try {
conn.setAutoCommit(false);
execute(conn,StringUtil.insertIntoDB(sql),datas);
conn.commit();
return true;
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("插入记录错误:" + e.getMessage());
System.out.println("错误的SQL语句为: " + sql.toString());
setMessage("插入记录错误:" + e.getMessage());
return false;
}
catch (Exception e) {
try {
conn.rollback();
}
catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("未知错误:" + e.getMessage());
System.out.println("错误时的SQL语句为: " + sql.toString());
System.out.print("错误时的插入数据为:" + datas);
setMessage("对不起,发生未知错误!\\n" + e.getMessage());
return false;
}
finally {
try {
if (conn != null) {
conn.setAutoCommit(true);
}
}
catch (SQLException e) {
System.out.println("恢复Connection对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
/**
* 执行查询列表操作
* @param querySql 要执行的sql语句
* @return 执行成功以Map的List对象形式返回查询结果,否则返回null
*/
public List queryList(String querySql) {
if (dsf == null) {
dsf = DataSourceFactory.create();
}
if (dsf == null) {
setMessage("对不起,创建数据源工厂对象失败。");
return null;
}
Connection conn = dsf.getConnection();
if (conn == null) {
setMessage("对不起,无法获取数据库连接。");
return null;
}
PreparedStatement ps = null;
ResultSet rs = null;
ResultSetMetaData rsmt = null;
List data = new ArrayList();
Object value;
try {
conn.setAutoCommit(false);
ps = conn.prepareStatement(StringUtil.insertIntoDB(querySql));
rs = ps.executeQuery();
rsmt = rs.getMetaData();
while (rs.next()) {
Map ht = new HashMap();
for (int i = 1; i <= rsmt.getColumnCount(); i++) {
int columnType = rsmt.getColumnType(i);
if (columnType != Types.BINARY
//&& columnType != Types.BLOB
&& columnType != Types.LONGVARBINARY
&& columnType != Types.VARBINARY) {
if (columnType == Types.CLOB) {
Clob clob = rs.getClob(i);
value = "";
if (clob != null) {
int valueLength = 65536;
StringBuffer tempValue = new StringBuffer("");
Reader re = clob.getCharacterStream();
char[] buffer = new char[65536];
while ((valueLength = re.read(buffer)) > 0) {
tempValue.append(buffer, 0, valueLength);
}
re.close();
value = tempValue.toString();
}
}
else if (columnType == Types.BLOB) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
InputStream bs = rs.getBinaryStream(i);
value = null;
if (bs != null) {
int valueLength = 65536;
byte[] buffer = new byte[65536];
while ((valueLength = bs.read(buffer, 0 ,65536)) > 0) {
ba.write(buffer,0, valueLength);
}
value = ba.toByteArray();
bs.close();
}
}
else if (columnType == Types.DATE) {
Timestamp ts = rs.getTimestamp(i);
if (ts != null) {
value =
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.MEDIUM,
Locale.CHINA).format(
ts);
}
else {
value = "";
}
}
else {
value = rs.getString(i);
}
ht.put(rsmt.getColumnName(i).toUpperCase(), (value == null ? "" :
((value instanceof String) ? StringUtil.fetchFromDB(value) : value)));
}
}
data.add(ht);
}
conn.setAutoCommit(true);
return data;
}
catch (Exception e) {
System.out.println("Sql语句执行错误:" + e.getMessage());
System.out.println("错误的Sql语句是:" + querySql);
setMessage("对不起,数据库查询失败:" + e.getMessage());
e.printStackTrace();
return null;
}
finally {
try {
conn.setAutoCommit(true);
if (ps != null) {
ps.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (rs != null) {
rs.close();
}
}
catch (SQLException e) {
System.out.println("关闭ResultSet对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
public Connection getConntent()
{
if (dsf == null) {
dsf = DataSourceFactory.create();
}
if (dsf == null) {
setMessage("对不起,创建数据源工厂对象失败。");
return null;
}
Connection conn = dsf.getConnection();
if (conn == null) {
setMessage("对不起,无法获取数据库连接。");
return null;
}
return conn;
}
public void closeConnection(Connection conn)
{
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
/**
* 执行查询单记录操作
* @param querySql 要执行的sql语句
* @return 执行成功以Hashtable对象形式返回查询结果,否则返回null
*/
public Map queryElement(String querySql) {
if (dsf == null) {
dsf = DataSourceFactory.create();
}
if (dsf == null) {
setMessage("Sorry,construct datasource factory failed!");
return null;
}
Connection conn = dsf.getConnection();
if (conn == null) {
setMessage("Sorry, the Connection object is null!");
return null;
}
PreparedStatement ps = null;
ResultSet rs = null;
ResultSetMetaData rsmt = null;
Map map = null;
Object value;
try {
conn.setAutoCommit(false);
ps = conn.prepareStatement(StringUtil.insertIntoDB(querySql));
rs = ps.executeQuery();
rsmt = rs.getMetaData();
if(rs.next()) {
map = new HashMap();
for (int i = 1; i <= rsmt.getColumnCount(); i++) {
int columnType = rsmt.getColumnType(i);
if (columnType != Types.BINARY
//&& columnType != Types.BLOB
//&& columnType != Types.LONGVARBINARY
//&& columnType != Types.VARBINARY
) {
if (columnType == Types.CLOB) {
Clob clob = rs.getClob(i);
value = "";
if (clob != null) {
int valueLength = 65536;
StringBuffer tempValue = new StringBuffer("");
Reader re = clob.getCharacterStream();
char[] buffer = new char[65536];
while ((valueLength = re.read(buffer)) > 0) {
tempValue.append(buffer, 0, valueLength);
}
re.close();
value = tempValue.toString();
}
}
else if (columnType == Types.DATE || columnType == Types.TIME || columnType == Types.TIMESTAMP) {
Timestamp ts = rs.getTimestamp(i);
if (ts != null) {
value =
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.MEDIUM,
Locale.CHINA).format(
ts);
}
else {
value = "";
}
}
else if (columnType == Types.BLOB) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
InputStream bs = rs.getBinaryStream(i);
value = null;
if (bs != null) {
int valueLength = 65536;
byte[] buffer = new byte[65536];
while ((valueLength = bs.read(buffer, 0 ,65536)) > 0) {
ba.write(buffer,0, valueLength);
}
value = ba.toByteArray();
bs.close();
}
}
else if (columnType == Types.LONGVARBINARY) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
InputStream bs = rs.getBinaryStream(i);
value = null;
if (bs != null) {
int valueLength = 65536;
byte[] buffer = new byte[65536];
while ((valueLength = bs.read(buffer, 0 ,65536)) > 0) {
ba.write(buffer,0, valueLength);
}
value = ba.toByteArray();
}
bs.close();
}
else {
value = rs.getString(i);
}
map.put(rsmt.getColumnName(i).toUpperCase(),(value == null ? "" :
((value instanceof String) ? StringUtil.fetchFromDB(value) : value)));
}
}
}
return map;
}
catch (Exception e) {
LogProxy.debug("Sql error:" + e.getMessage());
LogProxy.debug("The error sql is:" + querySql);
return null;
}
finally {
try {
if (ps != null) {
ps.close();
}
}
catch (SQLException e) {
System.out.println("Close prepareStatement error:" + e.getMessage());
}
try {
if (rs != null) {
rs.close();
}
}
catch (SQLException e) {
System.out.println("Close ResultSet error:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("Close Connection error:" + e.getMessage());
}
}
}
/**
* 执行查询单记录操作
* @param querySql 要执行的sql语句
* @return 执行成功以Hashtable对象形式返回查询结果,否则返回null
*/
public Map queryElementWithFormat(String querySql) {
if (dsf == null) {
dsf = DataSourceFactory.create();
}
if (dsf == null) {
setMessage("对不起,创建数据源工厂对象失败。");
return null;
}
Connection conn = dsf.getConnection();
if (conn == null) {
setMessage("对不起,无法获取数据库连接。");
return null;
}
PreparedStatement ps = null;
ResultSet rs = null;
ResultSetMetaData rsmt = null;
Map map = null;
Object value;
try {
conn.setAutoCommit(false);
ps = conn.prepareStatement(StringUtil.insertIntoDB(querySql));
rs = ps.executeQuery();
rsmt = rs.getMetaData();
if(rs.next()) {
map = new HashMap();
for (int i = 1; i <= rsmt.getColumnCount(); i++) {
int columnType = rsmt.getColumnType(i);
if (columnType != Types.BINARY
//&& columnType != Types.BLOB
//&& columnType != Types.LONGVARBINARY
//&& columnType != Types.VARBINARY
) {
if (columnType == Types.CLOB) {
Clob clob = rs.getClob(i);
value = "";
if (clob != null) {
int valueLength = 65536;
StringBuffer tempValue = new StringBuffer("");
Reader re = clob.getCharacterStream();
char[] buffer = new char[65536];
while ((valueLength = re.read(buffer)) > 0) {
tempValue.append(buffer, 0, valueLength);
}
re.close();
value = tempValue.toString();
}
}
else if (columnType == Types.DATE) {
Timestamp ts = rs.getTimestamp(i);
if (ts != null) {
value ="to_date('"+
DateFormat.getDateTimeInstance(
DateFormat.MEDIUM,
DateFormat.MEDIUM,
Locale.CHINA).format(
ts)+"','YYYY-MM-DD hh24:mi:ss')";
}
else {
value = "";
}
}
else if (columnType == Types.BLOB) {
Blob blob = rs.getBlob(i);
value = "";
if (blob != null) {
int valueLength = 65536;
byte[] tempValue = new byte[0];
InputStream ie = blob.getBinaryStream();
byte[] buffer = new byte[65536];
while ((valueLength = ie.read(buffer)) > 0) {
//tempValue.(buffer, 0, valueLength);
//tempValue = new byte[tempValue.length];
}
ie.close();
value = tempValue;
}
}
else if (columnType == Types.LONGVARBINARY) {
ByteArrayOutputStream ba = new ByteArrayOutputStream();
InputStream bs = rs.getBinaryStream(i);
value = null;
if (bs != null) {
int valueLength = 65536;
byte[] buffer = new byte[65536];
while ((valueLength = bs.read(buffer, 0 ,65536)) > 0) {
ba.write(buffer,0, valueLength);
}
value = ba.toByteArray();
}
bs.close();
}
else {
value = rs.getString(i);
}
map.put(rsmt.getColumnName(i).toUpperCase(),(value == null ? "" :
((value instanceof String) ? StringUtil.fetchFromDB(value) : value)));
}
}
}
return map;
}
catch (Exception e) {
System.out.println("Sql语句执行错误:" + e.getMessage());
System.out.println("错误的Sql语句是:" + querySql);
setMessage("对不起,数据库查询失败。\\n" + e.getMessage());
return null;
}
finally {
try {
if (ps != null) {
ps.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (rs != null) {
rs.close();
}
}
catch (SQLException e) {
System.out.println("关闭ResultSet对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
/**
* 记录日志
* @param operation
*/
public void log(String operation) {
}
// /**
// * 对字符串编码
// * @param sSource
// */
// public String escape(String sSource) {
// String sTarget = "";
// if (sSource == null) {
// return null;
// }
// for (int i = 0; i < sSource.length(); i++) {
// switch (sSource.charAt(i)) {
// case ' ' :
// sTarget += "%20";
// break;
// case ':' :
// sTarget += "%3A";
// break;
// /* case ' ':
// sTarget += "";
// break;
// case ' ':
// sTarget += "";
// break;*/
// default :
// sTarget += sSource.charAt(i);
// break;
// }
// }
// return sTarget;
// }
// /**
// * 对字符串编码
// * @param sSource
// */
// public String encode(String sSource) {
// String sTarget = "";
// if (sSource == null) {
// return null;
// }
// for (int i = 0; i < sSource.length(); i++) {
// switch (sSource.charAt(i)) {
// case ' ' :
// sTarget += " ";
// break;
// case '\"' :
// sTarget += """;
// break;
// default :
// sTarget += sSource.charAt(i);
// break;
// }
// }
// return sTarget;
// }
/**
* 设置出错信息
* @param theMessage 出错信息的内容
*/
public void setMessage(String theMessage) {
System.out.println("有错误发生:" + theMessage);
if (msg == null || msg.equals(""))
msg = theMessage;
else
msg = msg + "\\n" + theMessage;
}
/**
* 更新LOB类型的字段数据,包括BLOB类型和CLOB类型,该方法忽略BLOB和CLOB以外的字段
* @param table 要更新的数据库表名称
* @param data 包含要更新的数据的Hashtable对象,要求Hashtable对象中的Key值均为大写;<br>
* BLOB类型要求com.jspsmart.upload.File对象,CLOB类型要求String对象
* @param conditions 用于定位记录的条件
* @return boolean 若更新成功,则返回true,否则返回false
*/
public boolean updateLob(String table, Hashtable data, String conditions) {
if (table == null) {
System.out.println("没有指定更新表!");
return false;
}
if (data == null) {
System.out.println("没有指定要更新的数据!");
return false;
}
if (conditions == null) {
System.out.println("没有用于定位记录的条件!");
return false;
}
Hashtable newData = toUperCaseHashtable(data);
Connection conn = DataSourceFactory.create().getConnection();
if (conn == null) {
setMessage("对不起,获取数据库连接失败!");
return false;
}
StringBuffer sql = new StringBuffer("select ");
Enumeration items = newData.keys();
String item;
while (items.hasMoreElements()) {
item = items.nextElement().toString();
sql.append(item);
sql.append(",");
}
if (sql.charAt(sql.length() - 1) == ',')
sql.deleteCharAt(sql.length() - 1);
sql.append(" from ");
sql.append(table);
sql.append(" where ");
sql.append(conditions);
sql.append(" for update");
PreparedStatement pre = null;
ResultSet rs = null;
ResultSetMetaData rsmd = null;
try {
conn.setAutoCommit(false);
pre = conn.prepareStatement(StringUtil.insertIntoDB(sql.toString()));
rs = pre.executeQuery();
if (rs.next()) {
rsmd = rs.getMetaData();
BLOB blob = null;
CLOB clob = null;
for (int i = 1; i <= rsmd.getColumnCount(); i++) {
switch (rsmd.getColumnType(i)) {
/*case Types.BLOB :
blob = (BLOB) rs.getBlob(i);
if (blob != null) {
blob.trim(0);
OutputStream blobout = blob.getBinaryOutputStream();
blobout.write(((File) newData.get(rsmd.getColumnName(i))).getBytes());
blobout.flush();
blobout.close();
}
break;*/
case Types.CLOB :
clob = (CLOB) rs.getClob(i);
if (clob != null) {
clob.trim(0);
Writer clobWriter = clob.getCharacterOutputStream();
if (newData.get(rsmd.getColumnName(i)).toString().equals("")) {
clobWriter.write(" ");
}
else {
clobWriter.write(newData.get(rsmd.getColumnName(i)).toString());
}
clobWriter.flush();
clobWriter.close();
}
break;
default :
break;
}
}
conn.commit();
return true;
}
System.out.println("没有检索到要更新的记录!");
System.out.println("错误的SQL语句为: " + sql.toString());
return false;
}
catch (SQLException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("修改LOB数据时错误:" + e.getMessage());
System.out.println("错误的SQL语句为: " + sql.toString());
System.out.println("错误的数据为: " + data);
setMessage("对不起,插入记录发生错误!\\n" + e.getMessage());
return false;
}
catch (IOException e) {
try {
conn.rollback();
}
catch (SQLException e1) {
e1.printStackTrace();
}
System.out.println("文件数据读取错误:" + e.getMessage());
setMessage("对不起,文件数据读取发生错误!\\n" + e.getMessage());
return false;
}
catch (Exception e) {
try {
conn.rollback();
}
catch (Exception e1) {
e1.printStackTrace();
}
System.out.println("未知错误:" + e.getMessage());
System.out.println("错误时的SQL语句为: " + sql.toString());
System.out.println("错误的数据为: " + data);
setMessage("对不起,发生未知错误!\\n" + e.getMessage());
return false;
}
finally {
try {
if (pre != null) {
pre.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.setAutoCommit(true);
}
}
catch (SQLException e) {
System.out.println("恢复Connection对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
/**
* 执行数据库修改sql语句
* @param sql 要执行的sql语句
* @return boolean 执行成功返回true,否则返回false
*/
private boolean execute(String sql) {
if (dsf == null) {
dsf = DataSourceFactory.create();
}
if (dsf == null) {
setMessage("对不起,创建数据源工厂对象失败。");
return false;
}
Connection conn = dsf.getConnection();
if (conn == null) {
setMessage("对不起,无法获取数据库连接。");
return false;
}
sql = StringUtil.insertIntoDB(sql);
PreparedStatement ps = null;
try {
ps = conn.prepareStatement(sql);
ps.executeUpdate();
effRow=ps.getUpdateCount();
return true;
}
catch (Exception e) {
System.out.println("Sql语句执行错误:" + e.getMessage());
System.out.println("错误的Sql语句是:" + sql);
setMessage("对不起,数据库更新失败。\\n" + e.getMessage());
return false;
}
finally {
try {
if (ps != null) {
ps.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
/**
* 打印输出数组数据
* @param data 要打印的数组
*/
private String printArray(Object[] data) {
StringBuffer result = new StringBuffer("{").append(data[0].toString()).append("}");
for (int i = 1; i < data.length; i++) {
result.append(", {");
result.append(data[i].toString());
result.append("}");
}
return result.toString();
}
/**
* 字符串替换
*/
private String replaceString(String source, String find, String replace) {
StringBuffer result = new StringBuffer("");
int curIndex = source.indexOf(find);
while (curIndex >= 0) {
result.append(source.substring(0, curIndex));
result.append(replace);
source = source.substring(curIndex + find.length());
curIndex = source.indexOf(find);
}
return result.append(source).toString();
}
/**
* 设置指定字段的值
* @param conn java.sql.Connection 数据库连接对象
* @param pre java.sql.PreparedStatement 数据库PreparedStatement对象
* @param index 整型,指定要设置的字段的序号
* @param type 整型,指定要设置的字段的类型,值属于java.sql.Types
* @param columnValue 指定要设置的字段的值<br>
* BLOB类型或BINARY类型的字段要求com.jspsmart.upload.File对象<br>
* 其他类型的字段要求String对象
* @return PreparedStatement 返回设置好数据的PreparedStatement对象
* @throws SQLException 数据库访问失败时抛出SQLException
* @throws ParseException 日期、时间字符串格式错误时抛出ParseException
* @throws IOException 文件读取错误时抛出IOException
*/
private PreparedStatement setColumnValue(
Connection conn,
PreparedStatement pre,
int index,
int type,
Object columnValue)
throws SQLException, ParseException, IOException {
if ( (columnValue == null || columnValue.toString().equals(""))) {
pre.setNull(index, type);
}
else {
switch (type) {
case Types.BLOB :
pre.setObject(index, columnValue);
//pre.setBinaryStream(parameterIndex, x, length)
break;
case Types.BIGINT :
pre.setLong(index, Long.parseLong(columnValue.toString()));
break;
/*case Types.BINARY :
pre.setBinaryStream(
index,
new ByteArrayInputStream(((File) columnValue).getBytes()),
((File) columnValue).getSize());
break;*/
case Types.CHAR :
pre.setString(index, columnValue.toString());
break;
case Types.CLOB :
System.err.println("Clob数据大小 :"+((String)columnValue).length());
//pre.setObject(index, columnValue,Types.CLOB);
String temp = columnValue.toString();
int size =temp.length();
if(size>=1000 && size<=2010){
int offsetSize = 2000-size;
for(int i=0;i<=offsetSize;i++){
temp += " ";
}
}
System.out.println("clob size:"+temp.length());
//pre.setObject(index, columnValue);
pre.setCharacterStream(index,new CharArrayReader(temp.toCharArray()),
temp.toCharArray().length);
//pre.setCharacterStream(index,new java.io.StringReader(""+columnValue),((String)columnValue).length());
/*if(columnValue != null && !"".equals(""+columnValue)){
BASE64Encoder encode = new BASE64Encoder();
String temp = encode.encode(((String)columnValue).getBytes());
pre.setObject(index,temp );
}*/
break;
case Types.DATE :
if (columnValue.toString().equalsIgnoreCase("sysdate")) {
pre.setTimestamp(index, new Timestamp(Calendar.getInstance().getTime().getTime()));
}
else if (columnValue.toString().trim().length() < 11) {
pre.setDate(
index,
new Date(
DateFormat
.getDateInstance(DateFormat.MEDIUM, Locale.CHINA)
.parse(columnValue.toString())
.getTime()));
}
else {
if (columnValue.toString().indexOf(".") > 0) {
columnValue = columnValue.toString().substring(0, columnValue.toString().indexOf("."));
}
pre.setTimestamp(
index,
new Timestamp(
DateFormat
.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.CHINA)
.parse(columnValue.toString())
.getTime()));
}
break;
case Types.DECIMAL :
pre.setBigDecimal(index, BigDecimal.valueOf(Long.parseLong(columnValue.toString())));
break;
case Types.DOUBLE :
pre.setDouble(index, Double.parseDouble(columnValue.toString()));
break;
case Types.FLOAT :
pre.setFloat(index, Float.parseFloat(columnValue.toString()));
break;
case Types.INTEGER :
pre.setInt(index, Integer.parseInt(columnValue.toString()));
break;
case Types.LONGVARCHAR :
pre.setCharacterStream(
index,
new InputStreamReader(new ByteArrayInputStream(columnValue.toString().getBytes())),
columnValue.toString().getBytes().length);
break;
case Types.LONGVARBINARY :
pre.setBinaryStream(index,new ByteArrayInputStream((byte[]) columnValue),((byte[]) columnValue).length);
break;
case Types.NUMERIC :
pre.setBigDecimal(index, BigDecimal.valueOf(Long.parseLong(columnValue.toString().trim())));
break;
case Types.REAL :
pre.setDouble(index, Double.parseDouble(columnValue.toString()));
break;
case Types.SMALLINT :
pre.setShort(index, Short.parseShort(columnValue.toString()));
break;
case Types.TIME :
if (columnValue.toString().indexOf(".") > 0) {
columnValue = columnValue.toString().substring(0, columnValue.toString().indexOf("."));
}
pre.setTime(
index,
new Time(
DateFormat
.getTimeInstance(DateFormat.MEDIUM, Locale.CHINA)
.parse(columnValue.toString())
.getTime()));
break;
case Types.TIMESTAMP :
if (columnValue.toString().indexOf(".") > 0) {
columnValue = columnValue.toString().substring(0, columnValue.toString().indexOf("."));
}
pre.setTimestamp(
index,
new Timestamp(
DateFormat
.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.MEDIUM, Locale.CHINA)
.parse(columnValue.toString())
.getTime()));
break;
case Types.TINYINT :
pre.setByte(index, columnValue.toString().getBytes()[0]);
break;
/*case Types.VARBINARY :
pre.setBinaryStream(
index,
new ByteArrayInputStream(((File) columnValue).getBytes()),
((File) columnValue).getSize());
break;
*/
case Types.VARCHAR :
pre.setString(index, columnValue.toString());
break;
default :
pre.setNull(index, type);
break;
}
}
return pre;
}
/**
* 将Hashtalbe的Key值转换成大写
*/
private Hashtable toUperCaseHashtable(Hashtable data) {
Hashtable result = new Hashtable();
Enumeration items = data.keys();
String keyName = null;
while (items.hasMoreElements()) {
keyName = items.nextElement().toString();
result.put(keyName.toUpperCase(), data.get(keyName));
}
return result;
}
/**
* @return 返回执行update方法受影响的行数
* 必须在执行update行数后立即取得
*/
public int getEffRow() {
return effRow;
}
public String get_UniqueKey() {
Map keyID = this.queryElement("select incSqu.Nextval as newid from dual");
return (String) keyID.get("NEWID");
}
public int queryCount(String querySql) {
int count = 0;
if (dsf == null) {
dsf = DataSourceFactory.create();
}
if (dsf == null) {
setMessage("对不起,创建数据源工厂对象失败。");
return count;
}
querySql = StringUtil.insertIntoDB(querySql);
Connection conn = dsf.getConnection();
if (conn == null) {
setMessage("对不起,无法获取数据库连接。");
return count;
}
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn.setAutoCommit(false);
ps = conn.prepareStatement(querySql);
rs = ps.executeQuery();
if(rs.next()) {
count = rs.getInt(1);
}
return count;
}
catch (Exception e) {
System.out.println("Sql语句执行错误:" + e.getMessage());
System.out.println("错误的Sql语句是:" + querySql);
setMessage("对不起,数据库查询失败。\\n" + e.getMessage());
return count;
}
finally {
try {
if (ps != null) {
ps.close();
}
}
catch (SQLException e) {
System.out.println("关闭prepareStatement对象时错误:" + e.getMessage());
}
try {
if (rs != null) {
rs.close();
}
}
catch (SQLException e) {
System.out.println("关闭ResultSet对象时错误:" + e.getMessage());
}
try {
if (conn != null) {
conn.close();
}
}
catch (SQLException e) {
System.out.println("关闭Connection对象时错误:" + e.getMessage());
}
}
}
}
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
import javax.sql.DataSource;
import javax.naming.Context;
import javax.naming.InitialContext;
import com.sysoft.SysInfo;
/**
* 数据库连接管理对象,提供数据库连接的获取方法
*/
public class DataSourceFactory {
private static DataSourceFactory singleObject;
private static DataSourceFactory otherObject;
private String DataSourceName;
private DataSource m_ds ;
private String jndiUrl = SysInfo.jndiUrl;
/**
* Constructor for CheckConnection.
*/
private DataSourceFactory() {
try{
Properties prop = new Properties();
prop.setProperty(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
prop.setProperty(Context.PROVIDER_URL, jndiUrl);
Context initCtx = new InitialContext(prop);
if(initCtx == null )
throw new Exception("Boom - No Context");
m_ds = (DataSource)initCtx.lookup("SYOA_JNDI");
}catch(Exception ne){
System.out.println("[Exception][DBConn]"+ne);
}
}
/*
public DataSourceFactory(){
try{
Context initCtx = new InitialContext();
m_ds = (DataSource)initCtx.lookup("java:comp/env/SYOA_JNDI");
}catch(Exception ne){
System.out.println("[Exception][DBConn]"+ne);
}
}*/
private DataSourceFactory(String otherJndiName) {
try{
Properties prop = new Properties();
prop.setProperty(Context.INITIAL_CONTEXT_FACTORY,"weblogic.jndi.WLInitialContextFactory");
prop.setProperty(Context.PROVIDER_URL, jndiUrl);
Context initCtx = new InitialContext(prop);
if(initCtx == null )
throw new Exception("Boom - No Context");
m_ds = (DataSource)initCtx.lookup(otherJndiName);
}catch(Exception ne){
System.out.println("[Exception][DBConn]"+ne);
}
}
/**
* 创建DataSourceFactroy对象,该方法保证系统中只创建唯一一个DataSourceFactroy对象
* @return DataSourceFactroy对象的引用
*/
public static DataSourceFactory create() {
if (singleObject == null) {
singleObject = new DataSourceFactory();
}
return singleObject;
}
public static DataSourceFactory create(String otherJndiName) {
otherObject = null;
otherObject = new DataSourceFactory(otherJndiName);
return otherObject;
}
/**
* 获取数据库连接对象
* @return Connection对象,若获取连接失败,则返回null
*/
public Connection getConnection() {
if(m_ds!=null)
try {
Connection conn = m_ds.getConnection();
//if(conn == null){
// Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
// conn = DriverManager.getConnection("jdbc:oracle:thin:@166.1.3.139:1521:orcl","syoa","syoa");
return conn;
//}
} catch (SQLException e) {
// TODO 自动生成 catch 块
e.printStackTrace();
}catch(Exception e){
}
return null;
}
/**
* 获取数据源
* @return DataSource对象
*/
private DataSource getDataSource() {
return m_ds;
}
public static void main(String[] args) throws SQLException {
DataSourceFactory test = DataSourceFactory.create();
Connection conn = test.getConnection();
test.print("conn==null?"+(conn == null));
//test.print("dataSource==null?"+(test.dataSource()==null));
System.out.println(test.DataSourceName);
}
private void print(Object o){
System.out.println(o);
}
}
package com.sysoft.baseform.process.util;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import com.sysoft.baselib.BaseEntity;
public class StringUtil {
public static String cleanString(Object s){
if(s == null)
return "";
if(s instanceof String){
String t = (String)s;
if("null".equals(t.toLowerCase()))
return "";
return t.trim();
}
return "";
}
private static boolean DEBUG = true;
/**
* 从数据库中获取数据的编码转换
* @param source
* @return
*/
public static String fetchFromDB(Object source){
String sourceTemp = "";
if(source instanceof String)
sourceTemp = (String)source;
else if(source instanceof StringBuffer)
sourceTemp = ((StringBuffer)source).toString();
if(sourceTemp == null || sourceTemp.trim().equals(""))
return "";
String temp = sourceTemp.trim();
if(ControllInfo.IS_CONVERTION){
try {
return new String(temp.getBytes(ControllInfo.ISO_8859_1),ControllInfo.GB_2312);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return temp;
}
}else
return temp;
}
public static String transDecode(Object source){
String sourceTemp = "";
if(source instanceof String)
sourceTemp = (String)source;
else if(source instanceof StringBuffer)
sourceTemp = ((StringBuffer)source).toString();
if(sourceTemp == null || sourceTemp.trim().equals(""))
return "";
String temp = sourceTemp.trim();
if(true){
try {
return new String(temp.getBytes(ControllInfo.ISO_8859_1),ControllInfo.GB_2312);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return temp;
}
}else
return temp;
}
/**
* 入库前的编码转换
* @param source
* @return
*/
public static String insertIntoDB(String source){
if(source == null || source.trim().equals(""))
return "";
if(ControllInfo.IS_CONVERTION){
try {
return new String(source.getBytes(ControllInfo.GB_2312),ControllInfo.ISO_8859_1);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return source;
}
}else
return source;
}
/**
* 从数据库中获取数据的编码转换
* 转换每一个String字段, 必须有get、set方法
* @param object
* @param clazz
*/
public static void transFetchFromDB(Object object, Class clazz) {
if(ControllInfo.IS_CONVERTION){
if(object instanceof Collection) {
transFetchFromDB(((Collection)object).iterator(), clazz);
} else {
transObjectString(object, clazz, true);
}
}
}
public static void transFetchFromDB(Iterator it, Class clazz) {
if(ControllInfo.IS_CONVERTION){
while(it.hasNext()) {
transObjectString(it.next(), clazz, true);
}
}
}
/**
* 入库前的编码转换
* 转换每一个String字段, 必须有get、set方法
* @param object
* @param clazz
*/
public static void transInsertIntoDB(Object object, Class clazz) {
if(ControllInfo.IS_CONVERTION){
if(object instanceof Collection) {
transInsertIntoDB(((Collection)object).iterator(), clazz);
} else {
transObjectString(object, clazz, false);
}
}
}
public static void transInsertIntoDB(Iterator it, Class clazz) {
if(ControllInfo.IS_CONVERTION){
while(it.hasNext()) {
transObjectString(it.next(), clazz, false);
}
}
}
/**
* 转换
* @param object
* @param clazz
* @param isFromDB 表示是否是从数据库查询
*/
private static void transObjectString(Object object, Class clazz, boolean isFromDB) {
if(ControllInfo.IS_CONVERTION){
StringBuffer sb = new StringBuffer();
if(DEBUG) {
sb.append("****************************转码开始****************************\n");
sb.append(clazz);
if(isFromDB) {
sb.append(" 对象出库转换\n");
} else {
sb.append(" 对象入库转换\n");
}
}
Method[] methods = clazz.getMethods();
Set methodNamesSet = new HashSet();
for(int i = 0; i < methods.length; i++) {
methodNamesSet.add(methods[i].getName());
}
for(int i = 0; i < methods.length; i++) {
Method method = methods[i];
String methodName = method.getName();
Class returnType = method.getReturnType();
try {
//如果该方法为get方法并且返回类型为 String 则查找它对应的set方法,再转换字段编码
if (methodName.startsWith("get")/* && returnType != null && !clazz.equals(returnType)*/
&& (String.class.equals(returnType)/* || isBaseEntitySubClass(returnType)*/)) {
String methodNameOfSet = "s" + methodName.substring(1);
if(!methodNamesSet.contains(methodNameOfSet)) continue;
Method methodOfSet = clazz.getMethod(methodNameOfSet,
new Class[] { returnType });
//没找到对应参数为String的set方法,则不转换
if(methodOfSet == null) continue;
Object afterTrans = null;
Object beforeTrans = method.invoke(object, null);
if(isFromDB) {
afterTrans = fetchFromDB2(beforeTrans);
} else {
afterTrans = insertIntoDB2(beforeTrans);
}
methodOfSet.invoke(object, new Object[]{ afterTrans });
if(DEBUG) {
sb.append(methodName.substring(3, 4).toLowerCase() + methodName.substring(4) + ": ");
sb.append(beforeTrans + " --> " + afterTrans + "\n");
}
}
}catch(Exception e) {
e.printStackTrace();
}
}
if(DEBUG) {
sb.append("****************************转码结束****************************\n");
System.out.println(sb.toString());
}
}
}
/**
* fetchFromDB2 insertIntoDB2
* 是为了转换对象里面有属性为 BaseEntity类型的对象
* @param source
* @return
*/
private static Object fetchFromDB2(Object source){
if(source == null) return null;
if(ControllInfo.IS_CONVERTION){
if(source instanceof String) {
return fetchFromDB3((String)source);
}/* else if(source instanceof BaseEntity) {
transFetchFromDB(source, source.getClass());
return source;
} */else {
return source;
}
}else
return source;
}
/**
* fetchFromDB2 insertIntoDB2
* 是为了转换对象里面有属性为 BaseEntity类型的对象
* @param source
* @return
*/
private static Object insertIntoDB2(Object source){
if(source == null) return null;
if(ControllInfo.IS_CONVERTION){
if(source instanceof String) {
return insertIntoDB3((String)source);
}/* else if(source instanceof BaseEntity) {
transInsertIntoDB(source, source.getClass());
return source;
} */else {
return source;
}
}else
return source;
}
/**
* 从数据库中获取数据的编码转换
* @param source
* @return
*/
private static String fetchFromDB3(Object source){
String sourceTemp = "";
if(source instanceof String)
sourceTemp = (String)source;
else if(source instanceof StringBuffer)
sourceTemp = ((StringBuffer)source).toString();
if(sourceTemp == null || sourceTemp.trim().equals(""))
return sourceTemp;
String temp = sourceTemp;
if(ControllInfo.IS_CONVERTION){
try {
return new String(temp.getBytes(ControllInfo.ISO_8859_1),ControllInfo.GB_2312);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return temp;
}
}else
return temp;
}
/**
* 入库前的编码转换
* @param source
* @return
*/
private static String insertIntoDB3(String source){
if(source == null || source.trim().equals(""))
return source;
if(ControllInfo.IS_CONVERTION){
try {
return new String(source.getBytes(ControllInfo.GB_2312),ControllInfo.ISO_8859_1);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return source;
}
}else
return source;
}
private static boolean isBaseEntitySubClass(Class clazz) {
boolean b = false;
while(!Object.class.equals(clazz)) {
if(BaseEntity.class.equals(clazz)) {
return true;
} else {
if(clazz == null) return false;
clazz = clazz.getSuperclass();
}
}
return b;
}
}