1. 程式人生 > >每5秒向數據庫中插入一條記錄-學習筆記

每5秒向數據庫中插入一條記錄-學習筆記

每5秒向數據庫中插入一條記錄-學習筆記

import java.sql.SQLException; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; import cn.itcast.web.dao.SystemDao; //課程練習1 public class Demo3 { public static void main(String[] args) { Timer timer = new Timer(); timer.schedule(new YouTimerTask(),0,5*1000); } } //線程任務 class YouTimerTask extends TimerTask{ public void run() { try { SystemDao systemDao = new SystemDao(); systemDao.init("systemInit",UUID.randomUUID().toString()); } catch (SQLException e) { e.printStackTrace(); } } } /* drop table if exists systemInit; create table if not exists systemInit( id varchar(40) primary key, curr_time timestamp not null ); */ 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); } }

每5秒向數據庫中插入一條記錄-學習筆記