Java實現sqlserver2005的數據庫的備份與恢復

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.還原數據庫代碼(調用存儲過程)

    /**
     * 數據庫還原
     * @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    

PS:存儲過程創建在系統數據庫master下面,切記,否則會報錯

轉自:http://blog.csdn.net/tkd03072010/article/details/6668940

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章