首页 > IT职业 > IT生活 > 监听器-启动会初始化表 学习笔记:
数据库连接问题;后面采用固定写法:
/**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(); } }}
cn.xijie.listener.SystemListener
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); }}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/3112/viewspace-2814373/ ,如需转载,请注明出处,否则将追究法律责任。