Java实现sqlsever数据库备份与还原功能

Java实现sqlsever数据库备份与还原功能

1.连接数据库代码:

package com.once.xfd.dbutil;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DataBaseUtil {
	/**
	 * 获取数据库连接
	 * @return Connection 对象
	 */
	public static Connection getConnection() {
		Connection conn = null;
		try {
			Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
			String url = "jdbc:sqlserver://127.0.0.1:1433;databaseName=master";
			String username = "sa";
			String password = "123456";	
			conn = DriverManager.getConnection(url, username, password);
			
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return conn;
	}
	
	public static void closeConn(Connection conn) {
		if (conn != null) {
			try {
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	}
}

2.备份功能代码:


/**
     * 备份数据库
     * @return backup
     * @throws Exception
     */
public String backup() {
		ActionContext context = ActionContext.getContext();
		HttpServletRequest request = (HttpServletRequest) context
				.get(ServletActionContext.HTTP_REQUEST);
		String webtruepath = request.getParameter("path");
		String name = "dbname"; //数据库名
		try {
			File file = new File(webtruepath);
			String path = file.getPath() + "\\" + name + ".bak";// name文件名
			String bakSQL = "backup database 数据库名 to disk=? with init";// SQL语句
			PreparedStatement bak = DataBaseUtil.getConnection()
					.prepareStatement(bakSQL);
			bak.setString(1, path);// path必须是绝对路径
			bak.execute(); // 备份数据库
			bak.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "backup";
	}

3.还原功能代码(调用存储过程killrestore):


    /**
     * 数据库还原
     * @return recovery
     */
    public String recovery() {
        ActionContext context = ActionContext.getContext();
        HttpServletRequest request = (HttpServletRequest) context
                .get(ServletActionContext.HTTP_REQUEST);
        String webtruepath = request.getParameter("path");
        String name = "******";
        String dbname = "******";
        try {
            File file = new File(webtruepath);
            String path = file.getPath() + "\\" + name + ".bak";// name文件名
            String recoverySql = "ALTER   DATABASE   数据库名   SET   ONLINE   WITH   ROLLBACK   IMMEDIATE";// 恢复所有连接
            
            PreparedStatement ps = DataBaseUtil.getConnection()
                    .prepareStatement(recoverySql);
            CallableStatement cs = DataBaseUtil.getConnection().prepareCall("{call killrestore(?,?)}");
                cs.setString(1, dbname); // 数据库名
                cs.setString(2, path); // 已备份数据库所在路径
                cs.execute(); // 还原数据库
                ps.execute(); // 恢复数据库连接        
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "recovery";
    }

4.存储过程代码:


create proc killrestore (@dbname varchar(20),@dbpath varchar(40))       
as       
begin       
declare @sql   nvarchar(500)       
declare @spid  int       
set @sql='declare getspid cursor for select spid from sysprocesses where dbid=db_id('''+@dbname+''')'       
exec (@sql)       
open getspid       
fetch next from getspid into @spid       
while @@fetch_status <> -1       
begin       
exec('kill '+@spid)       
fetch next from getspid into @spid       
end       
close getspid       
deallocate getspid       
restore database @dbname from disk= @dbpath with replace
end    



你可能感兴趣的:(Java实现sqlsever数据库备份与还原功能)