首页 > 其他 > 详细

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

时间:2018-04-20 10:52:15      阅读:173      评论: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
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!