项目需求:定时备份数据库数据
1:pom文件添加依赖包
org.springframework
spring-context-support
4.2.0.RELEASE
org.springframework
spring-context-support
2.3.0
2:spring-mvc.xml文件
0 0 0 ? * L
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);
}