项目需求:定时备份数据库数据
1:pom文件添加依赖包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>4.2.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>2.3.0</version>
</dependency>
2:spring-mvc.xml文件
<!--创建任务->
<bean id="schedulerJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<!--指定执行任务的类-->
<property name="targetObject" ref="scheduleInfoAction"/>
<!--指定执行任务的方法-->
<property name="targetMethod" value="backupSqlserver"/>
</bean>
<!--定义触发时间-->
<bean id="cronTrigger" class="org.springframework.scheduling.quartz.CronTriggerFactoryBean">
<property name="jobDetail" ref="schedulerJobDetail"/>
<!--corn表达式-->
<property name="cronExpression">
<!--每周星期天的凌晨执行一次-->
<value>0 0 0 ? * L</value>
</property>
</bean>
<!--调度工厂-->
<bean id="scheduleFactory" class="org.springframework.scheduling.quartz.SchedulerFactoryBean" lazy-init="false">
<property name="triggers">
<list>
<ref local="cronTrigger"/>
</list>
</property>
</bean>
<!--执行业务方法-->
<bean id="scheduleInfoAction" class="com.benq.controller.ScheduleDataController"/>
3:ScheduleDataController执行任务类
public void backSqlserver(){
DataBase dataBase = new DataBase();
SimpleDateFormat sdf = new SimpleDateFormat("yyMMdd");
String now = sdf.format(new Date());
String backPath = configItemService.getBackupPath();
backPath = backPath + now + ".bak";
dataBase.setBackPath(backPath);
dataBase.setPort("1433");
dataBase.setUserName("***");
dataBase.setPassword("******");
dataBase.setDataBaseName("*******");
dataBase.setBackType(DataBase.SQLSERVER_INIT);
try {
BackSqlserver.executExport(dataBase);
} catch (Exception e) {
e.printStackTrace();
}
}
4:BackSqlserver的executeExport方法
public static void executExport(DataBase dataBase) throws Exception {
if(dataBase==null){
return;
}
File file = new File(dataBase.getBackPath());
if(!file.exists()){
file.getParentFile().mkdirs();
file.createNewFile();
}
Connection conn = getConnection(dataBase.getIp(),dataBase.getPort(),
dataBase.getUserName(),dataBase.getPassword());
String bakSQL = "backup database ? to disk=? with "+dataBase.getBackType();// SQL语句
PreparedStatement bak = conn.prepareStatement(bakSQL);
bak.setString(1, dataBase.getDataBaseName());// 数据库名
bak.setString(2, dataBase.getBackPath());// path必须是绝对路径
bak.execute(); // 备份数据库
bak.close();
closeConnection(conn);
}