天天看点

java 备份数据库

java 备份数据库1

首先我们要先写一个备份类

BackupDb.java

代码如下:

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.sql.SQLException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class BackupDb {

public BackupDb() {

}

public String backup() throws IOException {

  BufferedWriter mBufWriter = null;

//建立一个BackupDb.bat文件

  FileWriter fileWriter = new FileWriter("BackupDb.bat");

  mBufWriter = new BufferedWriter(fileWriter);

  String BackupDbUrl = "d://PostgreSQL8//bin//pg_dump.exe -U postgres -E utf8 test >";

  //取系统时间

  Date NowTimes = new Date();

  //将时间格式化成yyMMddhhmmss(年月日时分秒),例如200805010043   2008年5月1日0点43分。

  SimpleDateFormat sdf = new SimpleDateFormat("yyMMddhhmmss");

  String BackupDbName = "d://" + sdf.format(NowTimes) + ".sql";

  mBufWriter.write(BackupDbUrl);

  mBufWriter.write(BackupDbName);

  mBufWriter.newLine();

  mBufWriter.flush();

  mBufWriter.close();

  try {

   Runtime.getRuntime().exec("BackupDb.bat"); //执行BackupDb.bat文件进行备份数据库

  } catch (Exception e) {

   e.printStackTrace();

  }

  return BackupDbName;

}

}

然后我们在创建一个timer类,用来定时备份时间

TimerUse.java

代码如下:

package yifeng.com.org;

import java.text.SimpleDateFormat;

import java.util.*;

import java.io.*;

public class TimerUse {

public static void main(String[] args) {

  PickTask picktask = new PickTask();

  picktask .start(1, 60); //每60秒执行一次

}

}

class PickTask {

private Timer timer;

public PickTask() {

  timer = new Timer();

}

private TimerTask task = new TimerTask() {

  public void run() {

   Date date = new Date();

   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

   String beginDate = sdf.format(date);

   String beginTime = beginDate.substring(11, 16);

   System.out.println(beginDate);

   BackupDb bdb=new BackupDb();

   PrintLog pl=new PrintLog();

   //设定备份时间

   if (beginTime.equals("23:22")) {

    try {

     bdb.backup(); //执行文件备份

     String dbName=bdb.backup().toString(); //取出备份的文件名字

     String path="d://";

     int nameNo=dbName.lastIndexOf("//");

     File file=new File(path,dbName.substring(nameNo+1, dbName.length()));

     System.out.println(dbName.substring(nameNo+1, dbName.length()));

     //查看文件是否存在,以判断是否备份成功,写到备份日志里

     //注: 此处有点问题,明明备份成功,但是日志里却是位备份成功。不知道原因出在哪里

     //  在debug的时候写到日志里的就是备份文件成功。

     //  哪位高手能帮忙解决一下,在下不胜感激。

     //提示:其实这里还应该做些处理,如果未备份成功就应该重新备份。

     if(file.exists())

      pl.WriteLog(dbName+" 备份文件成功");

     else

      pl.WriteLog(dbName+" 未备份成功");

    } catch (FileNotFoundException e) {

     System.out.println("can not find the file");

    } catch (IOException e) {

     e.printStackTrace();

    }

   }

  }

};

public void start(int delay, int internal) {

  timer.schedule(task, delay * 1000, internal * 1000);

}

}

最后我们在写一个简单的备份日志类:

PrintLog.java

代码如下:

package yifeng.com.org;

import java.io.BufferedWriter;

import java.io.FileWriter;

import java.io.IOException;

import java.text.SimpleDateFormat;

import java.util.Date;

public class PrintLog {

public PrintLog(){

}

public void WriteLog(String log) throws IOException{

  BufferedWriter mbw = null;

//在D盘创建一个备份日志文件log。txt

  FileWriter fileWriter = new FileWriter("D://log.txt",true);

  mbw = new BufferedWriter(fileWriter);

  Date date=new Date();

  SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");

  String writeTime=sdf.format(date);

  mbw.write(writeTime+"   "); //写入时间

  mbw.write(log);       //写入日志内容

  mbw.newLine();

  mbw.flush();

  mbw.close();

}

}

java 备份数据库2

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.filechooser.FileFilter;
import java.sql.*;

class DataBackup implements ActionListener
{     JFrame f = null;
    JLabel label = null;
    JTextArea textarea = null;
    JFileChooser fileChooser = null;

    public DataBackup()
    {

        f = new JFrame("FileChooser Example");
        Container contentPane = f.getContentPane();
        textarea = new JTextArea();
        JScrollPane scrollPane = new JScrollPane(textarea);
        scrollPane.setPreferredSize(new Dimension(350,300));


        JPanel panel = new JPanel();
        JButton b1 = new JButton("恢复数据");
        b1.addActionListener(this);
        JButton b2 = new JButton("备份数据");
        b2.addActionListener(this);
        panel.add(b1);
        panel.add(b2);

        label = new JLabel(" ",JLabel.CENTER);

        contentPane.add(label,BorderLayout.NORTH);
        contentPane.add(scrollPane,BorderLayout.CENTER);
        contentPane.add(panel,BorderLayout.SOUTH);

        f.pack();
        f.setVisible(true);

        f.addWindowListener(new WindowAdapter() {
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });
    }

    public void actionPerformed(ActionEvent e)
    {
     //windows效果
     try
     {
      //UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
     }
     catch(Exception e1)
     {
      System.out.println("Look and Feel Exception");
      System.exit(0);
     }
        File file = null;
        int result;
        fileChooser = new JFileChooser("d://");
        fileChooser.addChoosableFileFilter(new JAVAFileFilter("bak"));

        //恢复数据库操作
        if (e.getActionCommand().equals("恢复数据"))
        {
            fileChooser.setApproveButtonText("确定");
            fileChooser.setDialogTitle("打开文件");
            result = fileChooser.showOpenDialog(f);

            textarea.setText("");

            if (result == JFileChooser.APPROVE_OPTION)
            {
                file = fileChooser.getSelectedFile();
            }
            else if(result == JFileChooser.CANCEL_OPTION)
            {
            }
            /***************执行事件*******************/
            //在这里写恢复数据库事件

            try
                {
                   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                }
                catch(ClassNotFoundException error)//驱动加载失败
                {
                 System.err.println("驱动加载失败");
                }
                //连接到数据库
                Connection conStudent;

                try
                {
                 conStudent = DriverManager.getConnection("jdbc:sqlserver://home:1433;DatabaseName=master","sa","");

                 Statement cmdStudent = conStudent.createStatement();

                 cmdStudent.execute("Restore Database HomeMIS from Disk='"+file.getPath()+"'");
                 if(conStudent != null)
                 {//关闭数据库连接
                    cmdStudent.close();
                    conStudent.close();
                 }
                }
                catch(SQLException sqlerr)
                {
                 System.out.println("Error:"+sqlerr.toString());
                }


        }

        //备份数据库操作
        if (e.getActionCommand().equals("备份数据"))
        {
            result = fileChooser.showSaveDialog(f);
            file = null;
            String fileName;

            if (result == JFileChooser.APPROVE_OPTION)
            {
                file = fileChooser.getSelectedFile();


                String fileName1 = file.getName();
                String filePath = file.getPath();
                int index = fileName1.lastIndexOf('.');
                if (index > 0)
                {
                 String extension = fileName1.substring(index+1).toLowerCase();

                    if(!extension.equals("bak"))
                    {
                     filePath = filePath + ".bak";
                    }
                }
                if (index < 0)
                {
                 filePath = filePath + ".bak";
                }
                /***************执行事件*******************/
                 //在这里写备份数据库事件
                 //装入JDBC驱动
                try
                {
                   Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver");
                }
                catch(ClassNotFoundException error)//驱动加载失败
                {
                 System.err.println("驱动加载失败");
                }
                //连接到数据库
                Connection conStudent;

                try
                {
                 conStudent = DriverManager.getConnection("jdbc:sqlserver://home:1433;DatabaseName=pubs","sa","");
                 Statement cmdStudent = conStudent.createStatement();
                 cmdStudent.execute("Backup Database HomeMIS To Disk='"+filePath+"'");
                 if(conStudent != null)
                 {//关闭数据库连接
                    cmdStudent.close();
                    conStudent.close();
                 }
                }
                catch(SQLException sqlerr)
                {
                 System.out.println("Error:"+sqlerr.toString());
                }


            }
            else if(result == JFileChooser.CANCEL_OPTION)
            {
            }

        }
    }

} //过滤文件
class JAVAFileFilter extends FileFilter
{     String ext;

    public JAVAFileFilter(String ext)
    {
        this.ext = ext;
    }

    public boolean accept(File file)
    {
        if (file.isDirectory())
            return true;

        String fileName = file.getName();
        int index = fileName.lastIndexOf('.');

        if (index > 0 && index < fileName.length()-1) {
            String extension = fileName.substring(index+1).toLowerCase();
            if (extension.equals(ext))
                return true;
        }
        return false;
    }

    public String getDescription(){
        if (ext.equals("bak"))
            return "Data Bakeup File (*.bak)";
        return "";
    }

    public static void main(String[] args)
    {
        new DataBackup();
    }
}