遇到问题:
数据库连接问题;后面采用固定写法:
解决问题
/**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); }}