码迷,mamicode.com
首页 > 其他好文 > 详细

监听器-启动会初始化表 学习笔记:

时间:2018-04-20 10:55:35      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:监听器-启动会初始化表 学习笔记:

遇到问题:

数据库连接问题;后面采用固定写法:

解决问题

   /**c3p0取得数据源*/
    public static DataSource  getDataSource() throws Exception  {

        ComboPooledDataSource cpds = new ComboPooledDataSource();
        cpds.setDriverClass("com.mysql.jdbc.Driver");
        cpds.setJdbcUrl("jdbc:mysql://192.168.47.196:3306/test");
        cpds.setUser("root");
        cpds.setPassword("123456");

        ComboPooledDataSource datasSource = cpds;

        return datasSource;

    }

监听器配置:


import java.util.Timer;
import java.util.TimerTask;
import java.util.UUID;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import cn.vote.dao.SystemDao;

public class SystemListener implements ServletContextListener {

    @Override
    public void contextInitialized(ServletContextEvent sce) {

        SystemDao systemDao = new SystemDao();
        try {
            systemDao.createTable("liwen");
            systemDao.init();
        } catch (Exception e) {

            e.printStackTrace();
        }
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {

        try {
            SystemDao systemDao = new SystemDao();
            systemDao.dropTable("liwen");
        } catch (Exception e) {

            e.printStackTrace();
        }

    }
}

web.xml配置

    <listener>
        <listener-class>cn.xijie.listener.SystemListener</listener-class>           
    </listener> 

Java代码


import java.sql.SQLException;

import org.apache.commons.dbutils.QueryRunner;

import cn.xijie.JdbcUtil.JdbcUtil;

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

        //创建表
        public void createTable(String tableName) throws Exception{
            QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
            String sql = "CREATE TABLE IF NOT EXISTS `"+tableName+"`(`runoob_id` INT UNSIGNED AUTO_INCREMENT,`runoob_title` VARCHAR(100) NOT NULL,`runoob_author` VARCHAR(40) NOT NULL,`submission_date` DATE,PRIMARY KEY ( `runoob_id` ))ENGINE=InnoDB DEFAULT CHARSET=utf8;";
            runner.update(sql);
        }

        //初始化数据
        public void init() throws Exception{
            QueryRunner runner = new QueryRunner(JdbcUtil.getDataSource());
            String sql = "INSERT INTO liwen(runoob_title, runoob_author, submission_date) VALUES (\"MySQL\", \"liwen\", NOW());";
            runner.update(sql);
        }

}

结果:
技术分享图片
成功

监听器-启动会初始化表 学习笔记:

标签:监听器-启动会初始化表 学习笔记:

原文地址:http://blog.51cto.com/357712148/2105629

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!