我写的一个锁封装类

文件 CWin32CriticalSection.h

#pragma once


class CWin32CriticalSection
{
public:

 CWin32CriticalSection(CRITICAL_SECTION& csInUse):m_csInUse(csInUse)
 {
 }

 ~CWin32CriticalSection()
 {
 }

 __forceinline void EnterInUse()
 {
  EnterCriticalSection(&m_csInUse);
 }

 __forceinline void LeaveInUse()
 {
  LeaveCriticalSection(&m_csInUse);
 }


private:
 CRITICAL_SECTION& m_csInUse;
};

class CSingleWaitWin32CS
{
public:
 CSingleWaitWin32CS(CRITICAL_SECTION& csInUse):cs(csInUse)
 {
  cs.EnterInUse();
 }

 ~CSingleWaitWin32CS()
 {
  cs.LeaveInUse();
 }

 CWin32CriticalSection cs;
};

class CWin32CS
{
public:
 CWin32CS(CRITICAL_SECTION& csInUse):cs(csInUse)
 {

 }
 ~CWin32CS()
 {
 }
 void Lock()
 {
  cs.EnterInUse();
 }

 void UnLock()
 {
  cs.LeaveInUse();
 }

 CWin32CriticalSection cs;
};

 

 用法:

class CTest
{
public:

 void Init();
 void UnInit();
 void Do1();
 void Do2();
 CRITICAL_SECTION m_cs;
};

void CTest::Init()
{
 InitializeCriticalSection(&m_cs); 
}
void CTest::UnInit()
{
 DeleteCriticalSection(&m_cs);
}

void CTest::Do1()
{
 CSingleWaitWin32CS cs1(m_cs);
 //do some thing
 ....
 ....
 ....
 ....
}

void CTest::Do2()
{
 CWin32CS  cs2(m_cs);
 cs2.Lock();
 //do some thing
 ....
 ....
 ....
 ....
 cs2.UnLock();
}

这是我自己写的一个DAO的封装类

07-19

因为项目使用JDBC,而且项目的规模不是很大,所以我就自己封装了一个JDBC的DAO,感觉也差不多了,不贴出来大家指点一下,有什么不足的及时指出,我会修正的,谢谢。rn[code=Java]import java.lang.reflect.Field;rnimport java.lang.reflect.Method;rnimport java.sql.Connection;rnimport java.sql.DriverManager;rnimport java.sql.PreparedStatement;rnimport java.sql.ResultSet;rnimport java.sql.ResultSetMetaData;rnimport java.sql.SQLException;rnimport java.sql.Timestamp;rnimport java.text.SimpleDateFormat;rnimport java.util.ArrayList;rnimport java.util.HashMap;rnimport java.util.List;rnimport java.util.Map;rnrnimport org.apache.log4j.Logger;rnrnimport com.toone.zct.exception.DataAccessFailureException;rn/**rn * 封装DAO层rn * @author chenchenrn * @since 2011-7-19rn */rn@SuppressWarnings("all")rnpublic class DBHelper rn private Connection conn;rn private PreparedStatement stmt;rn private ResultSet rs;rnrn private static Logger log = Logger.getLogger(DBHelper.class);rnrn public static DBHelper getInstance() rn Connection conn = TransactionUtil.getConnection();rn DBHelper dbHelper = new DBHelper();rn dbHelper.setConn(conn);rnrn return dbHelper;rn rn private void updateOrSaveAsObject(String pSql,Object pVO) throws DataAccessFailureException rn PreparedStatement pstmt = null;rn List fields = SqlUtil.parseFieldsFromInsert(pSql);rn log.debug("DB,_execupteUpdate,update sql =======" + pSql);rn try rn pstmt = conn.prepareStatement(pSql);rn pstmt = this.setPreparedStmt(pstmt,fields,pVO);rn int tt = pstmt.executeUpdate();rn rn catch (Exception ex) rn ex.printStackTrace();rn finally rn this.release();rn rn rnrn private PreparedStatement setPreparedStmt(PreparedStatement pstmt,rn List pFields, Object pVO) throws DataAccessFailureException rn for (int i = 0; i < pFields.size(); i++) rn String fieldName = (String) pFields.get(i);rn String getMethodName = "get"rn + fieldName.substring(0, 1).toUpperCase()rn + fieldName.substring(1);rn Class[] nullType = ;rn try rn Method getMethod = pVO.getClass().getDeclaredMethod(rn getMethodName, nullType);rn Object returnValue = getMethod.invoke(pVO, nullType);rn Class returnType = getMethod.getReturnType();rn if (returnType == java.lang.String.class) rn if (returnValue == null) rn pstmt.setString(i + 1, null);rn else rn pstmt.setString(i + 1, (String) returnValue);rn rn else if (returnType == int.class) rn if (returnValue == null) rn pstmt.setInt(i + 1, 0);rn else rn pstmt.setInt(i + 1, ((Integer) returnValue).intValue());rn rn else if (returnType == double.class) rn if (returnValue == null) rn pstmt.setDouble(i + 1, 0.00);rn else rn pstmt.setDouble(i + 1, ((Double) returnValue)rn .doubleValue());rn rn else if (returnType == float.class) rn if (returnValue == null) rn pstmt.setFloat(i + 1, 0.0f);rn else rn pstmt.setFloat(i + 1, ((Float) returnValue)rn .floatValue());rn rn else if (returnType == java.util.Date.class) rn if (returnValue == null) rn pstmt.setTimestamp(i + 1, null);rn else rn pstmt.setTimestamp(i + 1, new Timestamp(rn ((java.util.Date) returnValue).getTime()));rn rn else if (returnType == java.sql.Date.class) rn if (returnValue != null) rn pstmt.setTimestamp(i + 1, new Timestamp(rn ((java.sql.Date) returnValue).getTime()));rn else rn pstmt.setTimestamp(i + 1, null);rn rn else rn throw new DataAccessFailureException("没有处理的类型=="rn + returnType.getName());rn rn catch (SQLException ex) rn throw new DataAccessFailureException(ex.getMessage(), exrn .getErrorCode());rn catch (Exception ex) rn throw new DataAccessFailureException("" + ex.getMessage());rn rn rn return pstmt;rn rnrn /**rn * 只返回一个值的查询,返回结果集中的第一个数据,假如结果集为空则返回nullrn * rn * @param sqlrn * @param paramsrn * @returnrn */rn public Object getUniqueResult(String sql, Object... params) rn log.debug(sql);rn try rn stmt = conn.prepareStatement(sql);rn this.bindParameters(params);rn ResultSet rs = stmt.executeQuery();rn if (rs.next())rn return rs.getObject(1);rn elsern return null;rn catch (Exception e) rn e.printStackTrace();rn finally rn this.release();rn rn return null;rn rnrn /**rn * 查询rn * rn * @param sql sql语句rn * @param params 参数列表rn * @returnrn */rn public List> query(String sql, Object... params) rn log.debug(sql);rn try rn Map map = null;rn List> list = new ArrayList>();rnrn stmt = conn.prepareStatement(sql);rn this.bindParameters(params);rn ResultSet rs = stmt.executeQuery();rnrn ResultSetMetaData meta = rs.getMetaData();rnrn if (rs != null) rn while (rs.next()) rn map = new HashMap();rn for (int i = 0; i < meta.getColumnCount(); i++) rn map.put(meta.getColumnName(i + 1), rs.getObject(i + 1));rn rn list.add(map);rn rn rnrn return list;rn catch (Exception e) rn e.printStackTrace();rn finally rn this.release();rn rn return null;rn rnrn /**rn * 执行insert, update 和 delete语句rn * rn * @param sql sql语句rn * @param params 参数列表,必须和sql语句中的?数量一致rn * @returnrn */rn public int update(String sql, Object... params) rn log.debug(sql);rn try rn if (this.conn != null) rn stmt = conn.prepareStatement(sql);rn bindParameters(params);rn return stmt.executeUpdate();rn rn catch (Exception e) rn e.printStackTrace();rn finally rn this.release();rn rn return 0;rn rnrn /**rn * 绑定参数rn * rn * @param paramsrn * @throws SQLExceptionrn */rn private void bindParameters(Object... params) throws SQLException rn if (params != null) rn for (int i = 0; i < params.length; i++) rn stmt.setObject(i + 1, params[i]);rn rn rn rnrn /**rn * 释放资源rn */rn public void release() rn try rn if (rs != null) rn rs.close();rn rn if (stmt != null) rn stmt.close();rn rn catch (SQLException e) rn e.printStackTrace();rn rn rnrn /**rn * 获取连接对象rn * rn * @returnrn */rn public Connection getConn() rn return conn;rn rnrn public void setConn(Connection conn) rn this.conn = conn;rn rnrn /**rn * 创建连接对象rn * rn * @throws Exceptionrn */rn public Connection createConnection() throws Exception rn Class.forName("net.sourceforge.jtds.jdbc.Driver");rn conn = DriverManager.getConnection(rn "jdbc:jtds:sqlserver://10.1.29.204:1433/toone_zct;charset=gbk",rn "sa", "123");rn return conn;rn rnrn /**rn * 关闭数据库连接rn * rn * @param connrn * @throws DataAccessFailureExceptionrn */rn public void closeConnection(Connection conn)rn throws DataAccessFailureException rn try rn if (conn != null && !conn.isClosed()) rn conn.close();rn rn catch (SQLException ex) rn throw new DataAccessFailureException(ex.getMessage(), ex.getErrorCode());rn rn rnrn public List query(String pSql, Class pClazz)rn throws DataAccessFailureException rn ArrayList returnList = new ArrayList();rn Connection conn = null;rn PreparedStatement pstmt = null;rn ResultSet rst = null;rn log.debug("DB,query,query sql =======" + pSql);rn try rn conn = this.createConnection();rn pstmt = conn.prepareStatement(pSql);rn rst = pstmt.executeQuery();rn while (rst.next()) rn returnList.add(this.getVO(rst, pClazz));rn rn catch (Exception ex) rn ex.printStackTrace();rn finally rn this.release();rn rn return returnList;rn rnrn /**rn * 将存放在pRst中的一行记录取出来 存到pClazz的实例中rn * rn * @param pRstrn * @param pClazzrn * @returnrn * @throws DataAccessFailureExceptionrn */rn private Object getVO(ResultSet pRst, Class pClazz)rn throws DataAccessFailureException rn Object returnObject = null;rnrn try rn returnObject = pClazz.newInstance();rn catch (Exception ex) rn throw new DataAccessFailureException("db._getVO()== returnObject=="rn + ex.getMessage());rn rn Field[] fields = pClazz.getDeclaredFields();rn for (int i = 0; i < fields.length; i++) rn String fieldName = fields[i].getName();rn Class fieldType = fields[i].getType();rn String setMethodName = "set"rn + fieldName.substring(0, 1).toUpperCase()rn + fieldName.substring(1);rn Class[] type = fieldType ;rn try rn Method setMethod = pClazz.getMethod(setMethodName, type);rn Object paraValue = null;rn if (fieldType == String.class) // 由于tds原因(0个字符串的字段值取出以后变成了1个空格),只好做此判断rn String xx = pRst.getString(fieldName);rn if (xx != null) rn paraValue = xx.trim();rn rn else if (fieldType == int.class) rn paraValue = new Integer(pRst.getInt(fieldName));rn else if (fieldType == float.class) rn paraValue = new Float(pRst.getFloat(fieldName));rn else if (fieldType == double.class) rn paraValue = new Double(pRst.getDouble(fieldName));rn else if (fieldType == java.util.Date.class) rn SimpleDateFormat formatter = new SimpleDateFormat(rn "yyyy-MM-dd HH:mm:ss");rn String xx = pRst.getDate(fieldName).toString() + " "rn + pRst.getTime(fieldName).toString();rn paraValue = formatter.parse(xx);rn else if (fieldType == java.sql.Date.class) rn SimpleDateFormat formatter = new SimpleDateFormat(rn "yyyy-MM-dd HH:mm:ss");rn String xx = pRst.getDate(fieldName).toString() + " "rn + pRst.getTime(fieldName).toString();rn paraValue = new java.sql.Date(formatter.parse(xx).getTime());rn else rn paraValue = pRst.getObject(fieldName);rn rn Object[] paraValues = paraValue ;rn setMethod.invoke(returnObject, paraValues);rn catch (Exception ex) rn log.debug("db._getVO()==For==" + ex.getMessage());rn // throw new DataAccessFailureException("" + ex.getMessage());rn rn rn return returnObject;rn rn[/code]

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试

关闭