第二十章 JDBC DAO设计

解决UNITE数据库注释高unassigned率:手把手教你训练专属真菌分类器(含预训练模型分享) 本文针对使用UNITE数据库进行真菌ITS序列注释时出现的高未分配率问题,提供了详细的实战解决方案。通过对比vsearch直接注释与Naive Bayes分类器的原理差异,文章手把手指导读者在QIIME 2环境中训练专属分类器,包括数据准备、模型训练、参数优化及效果验证,并分享了预训练模型,旨在显著提升真菌群落分析的注释准确性和数据利用率。 阅读详情

第二十章 JDBC DAO设计


Connection的含义

    Connection表示了一个和数据库的链接,底层需要有操作系统的Socket支持,所以Connection是一种资源,既然是一种资源,就需要按照建立,打开,使用,关闭的顺序合理的使用。
    Connection是Java数据库操作的基础,是进行一系列操作的基础,所有的派生的操作,例如Statement,PreparedStatement,ResultSet等都由Connection直接或者间接的衍生。

    如何获得Connection呢?
    方法一,使用DriverManager类来获取,前提条件是数据库驱动程序需要在classpath下(即使用数据库链接的程序按照Java的方式可以访问到)。
       Connection conn = DriverManager.getConnection( "jdbc:oracle:thin:@192.168.0.1:1521:ORCL", user, pwd );
    方法二,使用数据库连接池来获取
       什么是数据库连接池呢,数据库连接池是标准JavaEE容器的一种服务,例如Webspher,Weblogic,Tomcat等,容器预先建立一些数据 库链接,以便应用程序使用的时候从中借取,注意有借有还,当应用程序使用完了之后会将数据库链接还回连接池。(数据源配置请参考其他文档)
       使用连接池的好处是,可以预先建立链接,减小在数据库获取上的相对时间。
       使用连接池获取数据库链接的方式为:
           InitialContext ctx = new InitialContext();
           DataSource ds = (DataSource)ctx.lookup("java:comp/env/jdbc/DataSource");
           Connection conn = ds.getConnection();
       由于在配置数据库连接池的时候已经定义了URL,用户名,密码等信息,所以在程序中使用的时候不需要传入这些信息。

ConnectionManager定义
    Connection用来专门管理数据库链接,通常情况下ConnectionManager只有一个方法,调用这个方法将返回一个Connection 的实例。通过ConnectionManager可以封装Connection的获取方式(例如开发的时候使用DriverManager,运用的时候使 用DataSource的方式,但是不需要修改ConnectionManager之外的其他代码)和追加Connection获取之前之后的操作(例如 针对Connection的属性的设置)。
    下面的代码是一个ConnectionManager的代码示例:

package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager {
   
    public static Connection getConnection() throws DaoException {
        Connection conn = null;
        try {
            conn = DriverManager.getConnection("", "", "");
        } catch (SQLException e) {
            throw new DaoException("can not get database connection", e);
        }
        return conn;
    }
}

    如果需要从开发模式变为运用模式,只需要将上述代码修改为:
package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager {
   
    public static Connection getConnection() throws DaoException {
        Connection conn = null;
        try {
             Context ctx = new InitialContext();
             DataSource ds = (DataSource)ctx.lookup("jdbc/dsname");
             conn = ds.getConnection();
          } catch(NamingException e) {
             throw new DaoException("can not find datasource", e);
          }catch (SQLException e) {
            throw new DaoException("can not get database connection", e);
        }
        return conn;
    }
}

如果需要预先设定Connection的一些属性,也可以在上述代码中设定,例如:
package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class ConnectionManager {
   
    public static Connection getConnection() throws DaoException {
        Connection conn = null;
        try {
             Context ctx = new InitialContext();
             DataSource ds = (DataSource)ctx.lookup("jdbc/dsname");
             conn = ds.getConnection();
                conn.setAutoCommit(false);
          } catch(NamingException e) {
             throw new DaoException("can not find datasource", e);
          }catch (SQLException e) {
            throw new DaoException("can not get database connection", e);
        }
        return conn;
    }
}

CommonDao定义
    属性和构造方法
       通常情况下,CommonDao要有一个Connection的引用。所有一个CommonDao的实例的所有方法的调用都需要依赖于这个 Connection。需要一个Connection的另外一个原因是如果各个方法需要保证在一个事务环境中(上下文中),必须保证所有的操作都在一个 Connection上。
       构造方法通常需要将类型为Connection的属性实例化,例如:

package com.jpleasure.jdbc.dao;

import java.sql.Connection;

public class CommonDao {
   
    private Connection conn;
   
    public CommonDao() throws DaoException {
        this.conn = ConnectionManager.getConnection();
    }   
}
   
    事务方法
        begin()
          开始一个事务,调用CommonDao的begin方法之后,所以的后续操作将会在一个事务环境内,要么全部提交,要么全部回滚。

        commit()
          提交一个事务,必须在begin调用之后调用。且和rollback方法互斥。

        rollback()  
          回滚一个事务,必须在begin方法调用之后调用。且和commit方法互斥。
   
       事务的实现有两种方法,一种是使用基于单一Connection的事务,另外一种方法是使用容器的JTA(Java Transaction API)。需要注意的是第一种方法可以在任何环境下使用,但是只能是针对单一的数据库链接。第二种方法智能在支持JTA的Java EE容器中使用(例如Websphere,Weblogic等,Tomcat默认不支持),但是支持多个Connection实例。
    第一种方法代码为:
package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.SQLException;

public class CommonDao {
   
    private Connection conn;
   
    public CommonDao() throws DaoException {
        this.conn = ConnectionManager.getConnection();
    }   

    public void begin() throws DaoException{
        if(conn != null) {
            try {
                conn.setAutoCommit(false);
            } catch (SQLException e) {
                throw new DaoException("can not begin transaction", e);
            }
        } else {
            throw new DaoException("connection not opened!");
        }
    }
   
    public void commit() throws DaoException {
        try {
            if (conn != null && !conn.getAutoCommit()) {
                conn.commit();
                conn.setAutoCommit(true);
            } else {
                if (conn == null) {
                    throw new DaoException("connection not opened!");
                } else {
                    throw new DaoException("first begin then commit please!");
                }
            }
        } catch (SQLException e) {
            throw new DaoException("can not commit transaction!", e);
        }
    }
   
    public void rollback() throws DaoException {
        try {
            if (conn != null && !conn.getAutoCommit()) {
                conn.rollback();
                conn.setAutoCommit(true);
            } else {
                if (conn == null) {
                    throw new DaoException("connection not opened!");
                } else {
                    throw new DaoException("first begin then rollback please!");
                }
            }
        } catch (SQLException e) {
            throw new DaoException("can not rollback transaction!", e);
        }
    }
   
   
}

    第二种我们在使用DAO的实例中介绍如何使用(@TODO)
       新建两个DAO,做不同的操作,使用JTA保证事务完整。

    查询方法
       查询方法也许是CommonDao最常用的方法,查询方法需要将数据库的结果返回给画面。返回值我们一般不使用ResultSet,因为 ResultSet依赖于Connection,如果Connection关闭,ResultSet将不再有效,所以我们通常将ResultSet转变为 一个List之后返回。
       在说明查询方法之前,我们先说说如何将数据库中的内容放在List中,我们使用一个List表示一个查询结果集合,使用一个Map表示集合中的一行,Map的key表示数据库表的字段名字,Value表示数据库字段的内容。代码为:
        private List convert(ResultSet rs) throws DaoException {

        // record list
        List retList = new ArrayList();

        try {
            ResultSetMetaData meta = rs.getMetaData();

            // column count
            int colCount = meta.getColumnCount();

            // each record
            while (rs.next()) {

                Map recordMap = new HashMap();

                // each column
                for (int i = 1; i <= colCount; i++) {
                    // column name
                    String name = meta.getColumnName(i);
                    // column value
                    Object value = rs.getObject(i);
                    // add column to record
                    recordMap.put(name, value);
                }
                // ad record to list
                retList.add(recordMap);
            }
        } catch (SQLException ex) {
            throw new DaoException("can not convert result set to list of map", ex);
        }
        return retList;
    }

    为了避免Sql注入的安全问题,我们通常使用PreparedStatement,在使用PreparedStatement的时候涉及到如何将传入参数设置到PreparedStatement上面,参看以下的共通方法:
    private void apply(PreparedStatement pstmt, List params) throws DaoException {
        try {
            // if params exist
            if (params != null && params.size() > 0) {
                // parameters iterator
                Iterator it = params.iterator();
               
                // parameter index
                int index = 1;
                while(it.hasNext()) {
                   
                    Object obj = it.next();
                    // if null set ""
                    if (obj == null) {
                        pstmt.setObject(index, "");
                    } else {
                        // else set object
                        pstmt.setObject(index, obj);
                    }
                   
                    //next index
                    index++;
                }
            }
        } catch (SQLException ex) {
            throw new DaoException("can not apply parameter", ex);
        }
    }

    接着我们继续说我们的查询方法,有了上述两个方法,我们的查询方法就非常简单了:
    public List query(String sql, List params) throws DaoException {
        List result = null;
        PreparedStatement pstmt = null;
        ResultSet rs = null;
        try {
            pstmt = conn.prepareStatement(sql);
            this.apply(pstmt, params);
            rs = pstmt.executeQuery();
            result = this.convert(rs);
        } catch (SQLException ex) {
            throw new DaoException("can not execute query", ex);
        } finally {
            if (rs != null) {
                try {
                    rs.close();
                } catch (SQLException e) {
                    // nothing
                }
            }
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    // nothing
                }
            }
        }

        return result;
    }
   
    特殊的查询方法(返回单值)
    有时候为了方便使用,我们需要返回单值的产寻方法,例如 select max(id) from table_a, select count(id) from table_b等。以下的代码使用了上述通用的查询方法,代码为:
    public Object queryOne(String sql, List params) throws DaoException {
        List list = this.query(sql, params);
       
        if(list == null || list.size() == 0) {
            throw new DaoException("data not exist");
        } else {
            Map record = (Map)list.get(0);
            if(record == null || record.size() == 0 ) {
                throw new DaoException("data not exist");
            } else {
                return record.values().toArray()[0];
            }
        }
    }
   
    更新,删除,插入方法
    由于在JDBC中这三个方法都是用了一个execute完成,所以这里我们也使用一个方法来完成这些功能。代码为:
    public int execute(String sql, List params) throws DaoException {
        int ret = 0;
        PreparedStatement pstmt = null;
        try {
            pstmt = conn.prepareStatement(sql);
            this.apply(pstmt, params);
            ret = pstmt.executeUpdate();
        }catch(SQLException ex) {
            throw new DaoException("", ex);
        } finally {
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    // nothing.
                }
            }
        }
       
        return ret;
    }
   
    批处理方法(查询)
    有些时候为了便于操作,需要一次查询多条SQL语句,我们称之为批处理,实现参看以下方法,其中为了和query方法做区分,将参数和返回值都改为了数组形式。

    public List[] queryBatch(String[] sqlArray, List[] paramArray) throws DaoException {
        List rets = new ArrayList();
        if(sqlArray.length != paramArray.length) {
            throw new DaoException("sql size not equal parameter size");
        } else {
            for(int i = 0; i < sqlArray.length; i++) {
                String sql = sqlArray[i];
                List param = paramArray[i];
                List ret = this.query(sql, param);
                rets.add(ret);
            }
            return (List[])rets.toArray();
        }
    }


    批处理方法(更新)
    有些时候需要一次更新多条Sql语句,为了便于操作,添加了批处理更新操作,参看以下代码,为了和更新方法区分,将参数和返回值都改为了数组形式。
    public int[] executeBatch(String[] sqlArray, List[] paramArray) throws DaoException {
        List rets = new ArrayList();
        if(sqlArray.length != paramArray.length) {
            throw new DaoException("sql size not equal parameter size");
        } else {
            for(int i = 0; i < sqlArray.length; i++) {
                int ret = this.execute(sqlArray[i], paramArray[i]);
                rets.add(new Integer(ret));
            }
           
            int[] retArray = new int[rets.size()];
            for(int i = 0; i < retArray.length; i++) {
                retArray[i] = ((Integer)rets.get(i)).intValue();
            }
           
            return retArray;
        }
    }


    资源释放
    由于CommonDao有一个Connection的属性,且Connection属于稀缺资源,所以在CommonDao不需要在使用的时候需要显示的关闭Connection。代码如下:
    public void close() throws DaoException{
        try {
            if (conn != null && conn.getAutoCommit()) {
                conn.close();
            } else {
                if(conn == null) {
                    throw new DaoException("can not close null connection, first new then close");
                } else {
                    throw new DaoException("transaction is running, rollbakc or commit befor close please.");
                }
            }
        } catch (SQLException ex) {
            throw new DaoException("Can not close common dao");
        }
    }
      
JDBC工具类(JDBCUtil Class)
    在上述的代码中我们看到有很多的无用的处理,例如:
            if (pstmt != null) {
                try {
                    pstmt.close();
                } catch (SQLException e) {
                    // nothing.
                }
            }
    为什么要有这些处理呢?说先这些处理发生的位置都是在正常处理完成之后,这些处理(例如pstmt.close())即使失败也没有影响,这个时候我们需 要做上述的无用处理,这正是JDBC API的一个小小的瑕疵。我们通常使用一个特殊的静态工具来来做补充,例如:

package com.jpleasure.jdbc.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class JDBCUtil {
    public void safelyClose(Connection conn) {
        if(conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                //
            }
        }
    }
    public void safelyClose(PreparedStatement pstmt) {
        if(pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                //
            }
        }
    }
    public void safelyClose(ResultSet rs) {
        if(rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                //
            }
        }
    }
}
 
异常处理
    也许细心的你已经发现了一个问题,为什么所有抛出异常的地方我们都是将SQLException包装在了DaoException之内抛出呢,为什么不直 接抛出SQLException呢?有两个原因,第一,可以细化,分类Exception抛出合适的异常,添加合适的消息,第二,隔离和Dao和业务逻辑 的耦合,可以方便的修改Dao层而不会影响到业务逻辑层。另外需要注意,DaoExcetion中可以包含SQLException,这个时候可以为客户 提供更详细的错误信息,例如ORA-12524等内容,但是很少见到。

package com.jpleasure.jdbc.dao;

public class DaoException extends Exception {

    public DaoException() {
        super();
    }

    public DaoException(String message, Throwable cause) {
        super(message, cause);
    }

    public DaoException(String message) {
        super(message);
    }

    public DaoException(Throwable cause) {
        super(cause);
    }
   
}

 
CANoe:入门介绍 CANoe网络通信分析:CANoe用户可以在台架上或者车辆中分析ECU和整个系统的多总线通信。Trace窗口:用于列出所有总线活动,例如消息或错误帧。对于每条消息,都可以显示单独的信号值Graphics窗口:用于在时间轴上以图形方式在线显示消息和诊断请求中传输的值,例如rpm或温度值Statistics窗口:用于显示有用的网络和节点统计信息,例如节点和帧级别的总线负载、突发计数器/持续时间、帧和错误的计数器/速率、控制器状态Data窗口:用于显示预选数据,例如数字或条形图数据。 阅读详情

相关推荐

MacOS蓝牙连接疑难杂症:从基础排查到高级修复全攻略

本文提供了一份全面的MacOS蓝牙故障排查与修复指南。从基础的菜单栏检查、终端命令诊断,到软/硬重启蓝牙服务、删除配置文件,再到使用blueutil工具、重置NVRAM等高级方法,系统性地解决了蓝牙无法连接、连接不稳定等常见问题。最后还分享了环境干扰排查、预防措施及硬件故障自检方法,帮助用户彻底解决Mac蓝牙连接难题。

weixin_29271263的博客 450

ResultSet转换为List的方法

方法一: ResultSet转换为List的方法 private static List convertList(ResultSet rs) throws SQLException { List list = new ArrayList(); ResultSetMetaData md = rs.getMetaData(); int columnCount = md.getColumnCo...

weixin_33691817的博客 804

S参数反演法

等效介质理论模型— 利用S参数反演法提取超材料结构的等效参数 等效介质理论模型—利用S参数反演法提取超材料结构的等效参数 S参数反演法,即利用等效模型的传输矩阵和S参数求解超材料结构的等效折射率n和等效阻抗Z的过程。本文对等效介质理论模型进行了详细介绍,并提供对应代码。 超材料的传输矩阵 超材料结构的传输矩阵函数为: 其中,d 为等效光学活性材料的厚度,n 为折射率,Z 表示阻抗。 S参数和传输矩阵T 超材料结构的S参数和传输矩阵T满足下列方程: 利用以上两式,可以得到等效折射率n和相对阻抗的表达式

weixin_43962864的博客 1万+

关于JDBC中增删改查接口的定义

在我们平常写代码的过程中,dao包下接口定义的方法返回值和参数经常会弄混,接下来我就把每个方法中的返回值和类型详细的讲一下,以便大家能更好的理解和运用接口中的方法 以Book对象为例: 查询所有: List<Book> allBook(); 因为查询所有不需要参数,所以没有参数。 查询所有需要返回多组数据,返回值类型为List集合 查询一条数据(根据id): Book findOne(int bookId); 需要根据id来查询,所以有一个int类型的参数。 返回的是一个Book对象,所以返

weixin_46503633的博客 318

ATE自动化测试设备:硬件与软件的完美协同

本文深入解析了ATE自动化测试设备如何通过硬件与软件的完美协同,实现高效、精准的电子产品测试。文章详细阐述了ATE系统的硬件架构(如测试控制器、仪器模块、开关矩阵)与软件层次(如测试管理、仪器控制、数据分析),并结合实战案例,揭示了软硬件协同设计在提升测试效率与可靠性中的关键作用。

weixin_29218509的博客 165

Revit获取族预览图

最近做到和族库相关的功能需要获取到族文件的预览图,在RevitAPI中提供了ElementType.GetPreviewImage方法,但是前提就是你是在Revit里面操作的,并且已经拿到了Symbol对象实例,才可以调用此方法。然后在网上找了另外一种方式,通过读取Revit文件,在REVITPREVIEW4.0字段截取文件信息,将其转换为图片格式。 一、使用RevitAPI中ElementType.GetPreviewImage方法 [Autodesk.Revit.Attributes.Transac.

weixin_44631419的博客 1749

mysql jdbc 如何获取id_JDBC 获取被插入数据的主键ID值

除了用存储过程还有以下方法可以获取:static int create() throws SQLException {Connection conn = null;PreparedStatement ps = null;ResultSet rs = null;try {// 2.建立连接conn = JdbcUtils.getConnection();// conn = JdbcUtilsSing...

weixin_42515364的博客 847

RLHF的数学表示

RLHF(Reinforcement Learning with Human Feedback)是一种结合了强化学习和人类反馈的机器学习方法。它通常用于训练智能体(agent)在复杂环境中做出决策,同时利用人类的反馈来指导和改进学习过程。RLHF 没有一个统一的数学表示式,因为它依赖于具体的应用场景和实现细节。然而,我们可以从强化学习和人类反馈的角度来描述RLHF的一些关键数学概念。

xw555666的博客 687

JAVA JDBC的单表查询通用dao层代码实现

获取数据库连接对象代码实 package com.eduask.util; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class DBUtil { private static Connection conn = null; pri

max_wcsdn的博客 3687

从封装到先进封装:一文讲透Chiplet、2.5D/3D堆叠与系统集成

封装是芯片产业链中连接硅片与电路板的桥梁,承担物理保护、电气连接、散热与机械支撑等核心任务。传统封装从DIP、QFP发展到BGA,通过提升引脚密度满足早期性能需求。随着摩尔定律放缓,单纯缩小晶体管尺寸难以为继,先进封装应运而生,其核心理念从“封装单颗芯片”转向“系统级高密度集成”。扇出型封装、2.5D硅中介层、3D堆叠、Chiplet和系统级封装等技术,通过微米级互连和垂直堆叠,大幅提升I/O密度与带宽,成为AI芯片、HBM存储、高性能计算等领域的关键支撑。本文梳理先进封装的技术演进、分层架构与工程难点,帮

weixin_29185167的博客 365

RK3568平台(平台总线篇)Gsensor STK8BA50

Gsensor,即加速度传感器(Accelerometer),是一种用于测量物体加速度的电子设备。以下是其关键点:1.工作原理MEMS技术:大多数Gsensor基于微机电系统(MEMS),通过检测质量块的位移来测量加速度。压电效应:部分Gsensor利用压电材料在受力时产生电压的特性来测量加速度。2.主要功能加速度测量:测量物体在X、Y、Z三个方向上的加速度。倾斜检测:通过重力加速度判断设备的倾斜角度。运动检测:识别设备的运动状态,如静止、移动、晃动等。震动检测:感知设备的震动或冲击。

weixin_49303682的博客 479

Java之JDBC之DAO 和增删改查通用方法-BasicDao的封装

文章目录1、DAO 和增删改查通用方法-BasicDao的封装1.1、 分析问题1.2、 基本说明1.3、 BasicDAO 应用实例1.4、小练习 1、DAO 和增删改查通用方法-BasicDao的封装 1.1、 分析问题 1.2、 基本说明 1.3、 BasicDAO 应用实例 JDBCUtilsByDruid.java package dao_.utils; import com.alibaba.druid.pool.DruidDataSourceFactory; import javax

一切随心走的博客 2704

基于Playwright与异步技术的公司评价智能爬取实战:以Glassdoor为例

本文将介绍一套基于最新Python技术的智能爬虫解决方案,使用Playwright实现浏览器自动化,结合异步编程和智能解析技术,高效抓取Glassdoor等平台的公司评价数据。我们不仅关注数据获取,更注重数据的结构化处理和反反爬虫策略的实现。

2201_76125261的博客 223

使用Struts2开发Java Web应用程序(目录)

配套源代码网站:https://teamware.dev.java.net 第一部分 Struts入门    第一章 Struts2 概览(beta)    第二章 一个简单的Login 应用程序(beta)       Struts 2 概要    第三章Struts配置(beta)        第三章 Struts配置(第一节 struts.properties配置)  

Struts 2 的专栏 7万+

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

NTscan扫描工具

ntscan是一个扫描器,可以扫描没有密码和弱密码的共享,先到配置文件中填写猜测的用户名和密码,扫描过程中右侧出现的是扫描日志。

使用Struts2开发Java Web应用程序

使用Struts2开发Java Web应用程序(目录) 收藏 配套源代码网站:https://teamware.dev.java.net第一部分 Struts入门    第一章 Struts2 概览(beta)    第二章 一个简单的Login 应用程序(beta)       Struts 2 概要    第三章Struts配置(beta)        第三章 Struts配

gotohbu的专栏 995

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

夯实Spring系列|总览介绍

文章目录系列文章1.文章说明2.整理目的3.Spring 核心特性4.数据存储(Data Access)5.Web 技术6.技术整合7.测试(Testing)8.Java 版本依赖于支持9.面试题9.1 Spring Framework 有哪些核心模块? 系列文章 夯实Spring系列|总览介绍 夯实Spring系列|夯实Spring系列|第一章:IoC到底什么是? 1.文章说明 本系列文...

谢文峰的博客 826

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

struts2开发web

[置顶] 使用Struts2开发Java Web应用程序(目录) 分类: Struts2 2007-08-01 22:12 57367人阅读 评论(48) 收藏 举报 strutsjavaweblocalizationjquerydojo 配套源代码网站:https://teamware.dev.java.net   第一部分 Struts入门     第一章 Struts2...

LIXG425的专栏 187

Struts2的专栏

第一部分 Struts入门    第一章 Struts2 概览(beta)    第二章 一个简单的Login 应用程序(beta)    第三章Struts配置(beta)        第三章 Struts配置(第一节 struts.properties配置)        第三章 Struts配置(第二节 Actin配置)        第三章 Struts配置(第三~七节其他配置)

518

Oracle学习笔记

Oracle 学习笔记目录 ❀Oracle部分 第一章 数据库介绍 3 第二章 Oracle简介 4 第三章 用户、权限 6 第四章 Oracle数据类型 8 第五章 SQL语句概述 9 第六章 表空间 11 第七章 表 12 第八章 函数 14 第九章 约束 17 第十章 单查询查询 22 第十一章 多表查询-内连接 23 第十二章 多表查询-外连接 25 第十三章

莫盐 6837
上一篇: 第二十二章Singleton和对象创建
下一篇: 第二十三章 Exception Architecture
struts2
博客等级 码龄19年 885粉丝 103原创
评论 9
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值