web每5秒向数据库中插入一条记录-学习笔记

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了web每5秒向数据库中插入一条记录-学习笔记相关的知识,希望对你有一定的参考价值。

SystemListener


import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import cn.itcast.web.dao.SystemDao;

public class SystemListener implements ServletContextListener {
    private Timer timer = new Timer();
    public void contextInitialized(ServletContextEvent sce) {
        try {
            SystemDao systemDao = new SystemDao();
            systemDao.createTable("systemInit");
            timer.schedule(new SystemTask(),0,5*1000);
        } catch (Exception e) {
        }
    }
    public void contextDestroyed(ServletContextEvent sce) {
        try {
            SystemDao systemDao = new SystemDao();
            systemDao.dropTable("systemInit");
            //中止定时器
            timer.cancel();
        } catch (Exception e) {
        }
    }
}
//任务类
class SystemTask extends TimerTask{
    public void run() {
        try {
            SystemDao systemDao = new SystemDao();
            systemDao.init("systemInit",UUID.randomUUID().toString());
        } catch (Exception e) {
        }
    }
}


*/

import java.sql.SQLException;
import org.apache.commons.dbutils.QueryRunner;
import cn.itcast.web.util.JdbcUtil;

public class SystemDao {
    //删除表
    public void dropTable(String tableName) throws SQLException{
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "drop table if exists " + tableName;
        runner.update(sql);
    }

    //创建表
    public void createTable(String tableName) throws SQLException{
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "create table if not exists "+tableName+"(id varchar(40) primary key,curr_time timestamp not null)";
        runner.update(sql);
    }

    //初始化数据
    public void init(String tableName,String id) throws SQLException{
        QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
        String sql = "insert into "+tableName+"(id) values(?)";
        runner.update(sql,id);
    }
}

web.xml配置

以上是关于web每5秒向数据库中插入一条记录-学习笔记的主要内容,如果未能解决你的问题,请参考以下文章

MongoDB快速入门学习笔记5 MongoDB的文档修改操作

插入排序学习笔记

利用jQuery Ajax技术实现每隔5秒向某页面传值

怎么实现客户端浏览器每隔30秒向服务器发送一次请求?

服务或意图服务每5秒向服务器无休止地发送位置更新?

[原创]java WEB学习笔记59:Struts2学习之路---OGNL,值栈,读取对象栈中的对象的属性,读取 Context Map 里的对象的属性,调用字段和方法,数组,list,map(代码片