Java实现数据库的备份和还原简易教程(SQL Server,零基础学起)

注意:以SQL Server2008为例。

1.安装sql server2008

下载地址:https://www.microsoft.com/en-us/download/confirmation.aspx?id=1695

64位系统选择“SQLEXPR_X64_ENU.exe",其他的根据自己使用的PC配置选择。

安装完打开Microsoft SQL Server Mangement Studio,如果提示连不上,则没有装成功,重新安装一遍就好了。

2.配置sql server

(1) 设置端口号

如下图所示:右击我的电脑->管理->Services and Apllications->SQL Server Configuration Manager->Protocols for SQlEXPRESS,将TCP/IP属性中的IPAll的TCP Dynamic Ports设为1433端口, 并将其Status改为Enabled。

(2) 重启SQL server service

如下图:

3. 创建存储过程killrestore

在master数据库下的Programmability下的Stored Procedures下创建存储过程。该存储过程实现还原数据库功能。传入两个参数:待还原数据库的名称和备份数据库的全路径(包含文件名)。

步骤:

(1) 右击“Stored Procedures”->选择“NewStored Procedures...”->新建的sql文件中替换成下面的代码。

ALTER PROCEDURE [dbo].[killrestore]( @dbname varchar(20), @dbpath varchar(100))
AS
BEGIN
	declare @sql nvarchar(500)
	declare @spid int
	set @sql='declare getspid cursor for select spid from master..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

(2) 保存该文件到默认目录下,文件名设为killrestore.sql。

(3) 刷新master,就能在“Stored Procedures”下找到名字为“dbo.killrestore”的文件。

注意:存储过程不能建在待还原的数据库中。

4. java代码实现部分

用到了jdbc driver,下载地址:https://www.microsoft.com/en-us/download/details.aspx?id=11774
选择tar.gz文件。

(1) 链接和关闭数据库:链接远程服务器192.168.2.150上的sql server数据库database_test

protected static Connection getConnection() {
	Connection conn = null;
	try {
		Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
		//sql 名称:database_test;如果是sql server在本机可将地址替换成127.0.0.1:1433,其中1433是sql server默认端口
		String url = "jdbc:sqlserver://192.168.2.150;databaseName=database_test";
		String userName = “holly”;
		String pwd = “123456”;
		conn = DriverManager.getConnection(url, userName, pwd);
	}catch (ClassNotFoundException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return conn;
}

protected static void closeConnection(Connection conn) {
		if (null != conn) {
			try {
				conn.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

(2) 判断远程服务器上的备份数据库文件是够存在

public static boolean isBackup() {
	String diskFilePath = “C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL10_50.MSSQLSERVER\\MSSQL\\Backup\\bak_test”;
	String diskFilePath = "http://192.168.2.150/”+diskFilePath;
	try {
		//注意:不能使用File的exists来判断,因为File exists智能判断本地的文件是否存在</span>
		URL url = new URL(diskFilePath);
		HttpURLConnection urlCon = (HttpURLConnection) url.openConnection();
		Long len = Long.parseUnsignedLong(urlCon.getHeaderField("Content-Length"));
		if(len>0){
			return true;
		}else {
			return false;
		}
	} catch (MalformedURLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
	return false;
}

(3) 备份数据库代码

备份远程服务器192.168.2.150上的sql server数据库database_test。
public static boolean backup() {
		//备份全路径,该路径是远程服务器上的		
		String diskFilePath = “C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL10_50.MSSQLSERVER\\MSSQL\\Backup\\bak_test”;
		String bakSql = "BACKUP DATABASE[database_test] TO DISK=N'" 
			+ diskFilePath + "'"
			+ " WITH NOFORMAT, NOINIT, NAME=N'database_test-Full Database Backup', SKIP, NOREWIND, NOUNLOAD, STATS=10";
		PreparedStatement ps = null;
		try {
			ps = getConnection().prepareStatement(bakSql);
			ps.execute();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				ps.close();
			} catch (SQLException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			}
		}
		return false;
	}

(4) 还原数据代码

还原数据库需要用上上面写的存储过程killrestore。
public static boolean restore() {
		String restoreSql = "ALTER DATABASE database_test SET ONLINE WITH ROLLBACK IMMEDIATE";
		PreparedStatement ps = null;
		Connection conn = getConnection();
		try {
			ps = conn.prepareStatement("USE master");//注意使用master下的存储过程。
			ps.execute();
			ps = conn.prepareStatement(restoreSql);
			CallableStatement cs = conn.prepareCall("{call killrestore(?,?)}");
			cs.setString(1, “database_test”);
			//此处路径是上面备份数据库文件的路径
 			cs.setString(2, "C:\\Program Files (x86)\\Microsoft SQL Server\\MSSQL10_50.MSSQLSERVER\\MSSQL\\Backup\\bak_test");
			cs.execute();
			ps.execute();
			return true;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		closeConnection(conn);
		return false;
	}



猜你喜欢

转载自blog.csdn.net/dzh0622/article/details/53026865
今日推荐