数据库自动备份与手动备份功能的实现
admin
2023-05-27 16:01:44
0

前端代码:

function createBackUp(){

var path=$("#path").val();

$.post("dataBack",{

'path' : path

}, function(data) {

if(data==1){

layer.msg("备份成功!",{time: 2000});

}else{

layer.msg("备份失败,该路径不存在!",{time: 2000});

}

}, "text");

}

后端实现:

package com.cloudshield.toolbox4.accountmanage.controller;


import java.io.File;

import java.io.IOException;

import java.io.InputStream;

import java.net.UnknownHostException;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.PreparedStatement;

import java.text.SimpleDateFormat;

import java.util.Properties;

import java.util.Timer;

import java.util.TimerTask;

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

import javax.servlet.http.HttpSession;

import org.springframework.context.annotation.Scope;

import org.springframework.stereotype.Controller;

import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestMethod;

import org.springframework.web.bind.annotation.ResponseBody;

import com.cloudshield.toolbox4.utils.DateUtils;

/**

 * 

 * @XXX

 * @date 2016-10-28 17:24

 *

 */

@Controller

@RequestMapping("/")

@Scope("prototype")

public class DataBackpController {

private static final int BACKUP_SUCCESS=1;/**表示备份成功*/

private static final int BACKUP_ERROR=0;/**表示备份失败*/

/**手动去备份*/

@ResponseBody

@RequestMapping(value="/dataBack",method = RequestMethod.POST)

public Integer dataBack(HttpServletRequest request,HttpSession session,String time){

Connection conn = null;

try{ /**读取备份路径*/

String path = request.getParameter("path");

/**读取配置文件*/

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("conn.properties");   

        Properties p = new Properties();

        try {   

        p.load(inputStream);   

        } catch (IOException e1) {   

        e1.printStackTrace();  

       

        /**获取用户名密码以及路径*/

        String driverName = p.getProperty("c3p0.driverClass");

        String userName=p.getProperty("c3p0.user");

        String passWord=p.getProperty("c3p0.password");

        String url = p.getProperty("c3p0.jdbcUrl");

        Class.forName(driverName).newInstance();

           conn= DriverManager.getConnection(url,userName,passWord);

           backData(path,getDbName(), conn,time);

           return BACKUP_SUCCESS;


}catch(Exception e){

e.printStackTrace();

          

}finally{

try{conn.close();}catch(Exception e){}

}

return BACKUP_ERROR;

}

/**时间设置自动备份*/

@ResponseBody

@RequestMapping(value="/setAutoBackUp",method = RequestMethod.POST)

public Integer setAutoBackUp(HttpServletRequest request,HttpSession session){

try{

Timer timer = new Timer();

final String setupstime = request.getParameter("time");

final String path = request.getParameter("path");

TimerTask task =new TimerTask(){

public void run(){

Connection conn = null;

/**读取配置文件*/

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("conn.properties");   

Properties p = new Properties();

try {   

p.load(inputStream);  

/**获取用户名密码以及路径*/

String driverName = p.getProperty("c3p0.driverClass");

String userName=p.getProperty("c3p0.user");

String passWord=p.getProperty("c3p0.password");

String url = p.getProperty("c3p0.jdbcUrl");

Class.forName(driverName).newInstance();

conn= DriverManager.getConnection(url,userName,passWord);

backData(path,getDbName(),conn,setupstime);

} catch (Exception e1) {   

e1.printStackTrace();  

}finally{

try{conn.close();}catch(Exception e){}

}

}

             

};

if(setupstime!=null&&setupstime.equals("oneday")){

timer.scheduleAtFixedRate(task,DateUtils.getOneday(),DateUtils.getOneday());

}

if(setupstime!=null&&setupstime.equals("week")){

timer.scheduleAtFixedRate(task,DateUtils.getWeek(),DateUtils.getWeek());

}

if(setupstime!=null&&setupstime.equals("halfamonth")){

timer.scheduleAtFixedRate(task,DateUtils.getHalfamonth(),DateUtils.getHalfamonth());

}

if(setupstime!=null&&setupstime.equals("onemonth")){

timer.scheduleAtFixedRate(task,DateUtils.getMonth(),DateUtils.getMonth());

}

if(setupstime!=null&&setupstime.equals("halfayear")){

timer.scheduleAtFixedRate(task,DateUtils.getHalfayear(),DateUtils.getHalfayear());

}

if(setupstime!=null&&setupstime.equals("oneyear")){

timer.scheduleAtFixedRate(task,DateUtils.getOneYear(),DateUtils.getOneYear());

}

return BACKUP_SUCCESS; 


}catch(Exception e){

e.printStackTrace();

          

}

return BACKUP_ERROR;

}

/**备份方法*/

public String backData(String path,String db_name,Connection conn,String time) throws Exception{

/**要返回备份名称*/

String bk_name = "";

        /**与数据库进行操作*/

PreparedStatement stmt = null;

        String sql = "";

        try{

        File databasePath = new File(path);

        if(!databasePath.exists()){

        databasePath.mkdir();

        databasePath.setWritable(true);

        }

        String file = new SimpleDateFormat("yyyyMMddHHmmss").format(new java.util.Date())+".bak";

            if(time!=null&&time!=""){

            file="zdbf"+file;

        }

            File newFile=new File(path+File.separator+file);

            newFile.createNewFile();

            newFile.setWritable(true);

            sql = "backup database "+db_name+" to disk=N'"+path+File.separator+file+"' with format,name=N'full backup of "+db_name+"'";

            stmt = conn.prepareStatement(sql);

            stmt.executeUpdate();

            bk_name = file; 

        }catch(Exception e){

            e.printStackTrace();

            throw e;

        }

        finally

        {

        try{stmt.close();} catch(Exception e){}

        }

        return bk_name;

    }

/**获取要备份的数据库名字*/

public String getDbName(){

/**读取配置文件*/

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("other.properties");   

    Properties p = new Properties();

    try {   

    p.load(inputStream);   

    } catch (IOException e1) {   

    e1.printStackTrace();  

   

    String dbname=p.getProperty("dbName");

   

    return dbname;

}

/**这里不指定post或者get方式的话,默认2中方式都可以*/

@RequestMapping(value = "/autoBackupPage", produces="text/html;charset=UTF-8")

public String autoBackupPage(HttpServletRequest request, HttpServletResponse response) throws UnknownHostException, IOException{

return "jsp/accountManage/backupWindow";

}

/**跳转数据备份的主页面*/

@RequestMapping(value = "/toBackupPage", produces="text/html;charset=UTF-8")

public String toBackupPage(HttpServletRequest request, HttpServletResponse response) throws UnknownHostException, IOException{

return "jsp/accountManage/backUp";

}

}

相关内容

热门资讯

马斯克:地球最强硬件公司仅Sp... 快科技8月5日消息,北京时间8月5日,SpaceX召开2026年第二季度财报电话会议。 SpaceX...
原创 一... 韦布空间望远镜对海王星的卫星和星环进行的新观测,揭示了太阳系边缘这颗行星在数十亿年前经历的一场灾难。...
声网联合爱芯元智推出机器人实时... 近日,声网与全球领先的AI系统芯片(SoC)供应商爱芯元智联合宣布,基于爱芯元智 AX8850N S...
巴西总统:美国撤销驻美大使签证... 当地时间5日上午,巴西总统卢拉在官邸接受采访时表示,美国政府撤销巴西驻美大使签证的决定“不负责任、考...
汉艺精密取得一种直线导轨专利,... 国家知识产权局信息显示,东莞市汉艺精密机械有限公司取得一项名为“一种直线导轨”的专利,授权公告号CN...
40余名台湾青年在闽研学AI电... 漳州8月5日电 (记者 张金川)8月5日,40余名台湾青年在福建省漳州市云霄县圆满结束了他们为期五天...
AI智能体能替你谈判账单吗?实... 用AI来协商经常性账单的费率,是那种永远排在待办清单末尾的琐事。即便每年费用都在上涨,大多数人还是选...
陕西柞水遭遇大暴雨,五千余户群... 8月5日7时至15时,陕西省商洛市柞水县出现大到暴雨、局地大暴雨,杏坪社区地质站最大降雨量135.4...
伊朗与阿曼会谈最新细节曝光 美国有线电视新闻网(CNN)8月5日报道,伊朗和阿曼将敲定一项关于通过霍尔木兹海峡进行商业航运的框架...
大科学装置建设全面提速 创新成... 央视网消息(新闻联播):重大科技基础设施是建设科技强国的利器。今年以来,我国大科学装置建设全面提速,...