使用VB.net实现sql数据库的备份与恢复代码

使用VB.net实现sql数据库的备份与恢复代码,第1张

Private Sub Button _Click(ByVal sender As System Object ByVal e As System EventArgs) Handles Button Click 备份数据库 BACKUP DATABASE Test TO DISK= C:\Backup WITH Format Dim cn As SqlConnection Dim cm As SqlCommand cn = getDB() cm = New SqlCommand( BACKUP DATABASE JXbase TO DISK= C:\Backup WITH Format cn) cn Open() cm ExecuteNonQuery() MsgBox( 备份成功 ) cn Close()

End Sub

恢复 Private Sub Button _Click(ByVal sender As System Object ByVal e As System EventArgs) Handles Button Click Dim cn As New SqlConnection Dim cn As New SqlConnection Dim mydr As SqlDataReader Dim str As String

Dim tmpConnectionString As String = Data Source=JJKInitial Catalog=masterIntegrated Security=True cn ConnectionString = tmpConnectionString cn ConnectionString = tmpConnectionString cn Open() cn Open() Dim cm As SqlCommand = New SqlCommand( select spid from master sysprocesses where dbid=db_id( JXbase ) cn) mydr = cm ExecuteReader()

Dim cm As SqlCommand = New SqlCommand() cm Connection = cn

While (mydr Read()) 杀死进程

str = kill &mydr( spid ) ToString() cm CommandText = str cm CommandType = CommandType Text Application DoEvents() cm ExecuteNonQuery() 杀进程 End While mydr Close() cm = New SqlCommand( RESTORE DATABASE JXbase FROM DISK= C:\Backup cn) 恢复备份 cm ExecuteNonQuery() MsgBox( 恢复成功成功 ) cn Close() cn Close()

lishixinzhi/Article/program/net/201311/12901

传统方法用SQL Server作数据库后台时,一般采用手工的方式利用SQL Server自身提供的可视化工具或SQL语言进行数据的备份还原功能(余正涛等,2003),但是由于SQL Server 的复杂性, *** 作比较繁琐,就使得普通用户对数据的备份与还原有一定的困难,并且容易造成错误,可能造成数据丢失等灾难性的后果。考虑到系统完整性和可靠性,可在VB 6.0环境下实现SQL Server数据库的备份与还原工作。

(一)实现思路

为了通过程序实现数据库备份与还原工作,必须在VB环境下引用SQLDMO,SQLDMO(SQL Distributed Management Objects,SQL 分布式管理对象)封装了Microsoft SQL Server数据库中的对象。SQLDMO是Microsoft SQL Server中企业管理器所使用的应用程序接口(包括备份和恢复),允许用支持自动化或COM 的语言编写应用程序。SQLDMO 对象来自SQLDMO.dll,SQLDMO.dll 是随 SQL Server 2000 一起发布的。并通过CreateObject("SQLD MO.SQLServer")函数创建新对象,使用SQLServ er.Connect函数经密码校验可连接服务器,再创建备份核心对象SQLDMO.Backup,同时指定备份文件等参数即可实现数据库备份与还原。具体的备份处理流程如图8-10所示。

特别注意SQL Server 2000 所安装的硬盘分区格式是否是NTFS格式,NTFS是最适合安装SQL Serv⁃er的文件系统。它比FAT文件系统更稳定且更容易恢复。而且它还包括一些安全选项,例如文件和目录ACL,以及文件加密(EFS)。如果是Fat32格式建议将它改成NTFS格式,因为Fat32支持最大文件为4G,数据库超过4G通常会提示日志文件太大之类的错误。

图8-10 数据库备份处理流程图

(二)关键代码

'************数据库备份 *** 作*************

Set gSQLServer=getSQLServer(ServerName,UserName,password)

Private Function BackUpData(gDatabaseName As String,gBkupRstrFileName As String,Server⁃Name As String,UserName As String,password As String)As String

On Error GoTo ErrHandler:

Dim oBackup As SQLDMO.Backup

Dim gSQLServer As SQLDMO.SQLServer

Set tprg=New CProgress

tprg.Title ="正在执行数据库备份......"

ServerName为服务器名称;serName为用户名;password为超级密码

'连接服务器

Set oBackup=New SQLDMO.Backup

Set oBackupEvent=oBackup

gDatabaseName为所要备份数据名称;gBkupRstrFileName为备份文件名

oBackup.Database=gDatabaseName

oBackup.Files=gBkupRstrFileName

已存在gBkupRstrFileName备份文件名,则覆盖

If Len(Dir(gBkupRstrFileName))>0 Then

Kill(gBkupRstrFileName)

End If

oBackup.PercentCompleteNotification=1

Screen.MousePointer=vbHourglass

oBackup.SQLBackup gSQLServer

DoEvents

Screen.MousePointer=vbDefault

'清空内存、关闭连接

Set oBackupEvent=Nothing

Set oBackup=Nothing

gSQLServer.Close

Set gSQLServer=Nothing

Set tprg=Nothing

Exit Function

ErrHandler:

m_str状态=Err.Description

Resume Next

Set tprg=Nothing

End Function

'************数据库还原 *** 作*************

Private Function RestoreData(gDatabaseName As String,gBkupRstrFileName As String,Server⁃Name As String,UserName As String,password As String)As String

On Error GoTo ErrHandler:

Dim oRestore As SQLDMO.Restore

Dim msg As String

Dim Response As String

Set tprg=New CProgress

tprg.Title ="正在执行数据库还原......"

Dim gSQLServer As SQLDMO.SQLServer

'ServerName为服务器名称;serName为用户名;password为超级密码

'连接服务器

Set gSQLServer=getSQLServer(ServerName,UserName,password)

Set oRestore=New SQLDMO.Restore

Set oRestoreEvent=oRestore

'gDatabaseName为所要还原数据名称;gBkupRstrFileName为还原文件名

oRestore.Database=gDatabaseName

oRestore.Files=gBkupRstrFileName

Screen.MousePointer=vbHourglass

oRestore.PercentCompleteNotification=1

oRestore.SQLRestore gSQLServer

Screen.MousePointer=vbDefault

'清空内存、关闭连接

Set oRestoreEvent=Nothing

Set oRestore=Nothing

gSQLServer.Close

Set gSQLServer=Nothing

Set tprg=Nothing

Exit Function

ErrHandler:

m_str状态=Err.Description

Resume Next

Set tprg=Nothing

End Function

'************显示备份进度*************

'************显示还原进度*************

End Sub

Private Sub oBackupEvent_PercentComplete(ByVal Message As String,ByVal Percent As Long)

DoEvents

tprg.Value=Percent

End Sub

Private Sub oRestoreEvent_PercentComplete(ByVal Message As String,ByVal Percent As Long)

DoEvents

tprg.Value=Percent

MySQL的一些前台工具是有备份恢复功能的,可是如何在我们的应用程序中实现这一功能呢?本文提供了示例代码来说明如何使用Java代码实现MySQL数据库的备份恢复。

本次实现是使用了MySQL数据库本身提供的备份命令mysqldump和恢复命令mysql,在java代码中通过从命令行调用这两条命令来实现备份和恢复。备份和恢复所使用的文件都是sql文件。

本代码是参照网上某网友提供的源码完成的。

[java] view plaincopy

package xxx.utils

import java.io.BufferedReader

import java.io.File

import java.io.FileInputStream

import java.io.FileNotFoundException

import java.io.FileOutputStream

import java.io.IOException

import java.io.InputStream

import java.io.InputStreamReader

import java.io.OutputStream

import java.io.OutputStreamWriter

import java.io.PrintWriter

import java.io.UnsupportedEncodingException

/**

* MySQL数据库的备份与恢复 缺陷:可能会被杀毒软件拦截

*

* @author xxx

* @version xxx

*/

public class DatabaseBackup {

/** MySQL安装目录的Bin目录的绝对路径 */

private String mysqlBinPath

/** 访问MySQL数据库的用户名 */

private String username

/** 访问MySQL数据库的密码 */

private String password

public String getMysqlBinPath() {

return mysqlBinPath

}

public void setMysqlBinPath(String mysqlBinPath) {

this.mysqlBinPath = mysqlBinPath

}

public String getUsername() {

return username

}

public void setUsername(String username) {

this.username = username

}

public String getPassword() {

return password

}

public void setPassword(String password) {

this.password = password

}

public DatabaseBackup(String mysqlBinPath, String username, String password) {

if (!mysqlBinPath.endsWith(File.separator)) {

mysqlBinPath = mysqlBinPath + File.separator

}

this.mysqlBinPath = mysqlBinPath

this.username = username

this.password = password

}

/**

* 备份数据库

*

* @param output

*输出流

* @param dbname

*要备份的数据库名

*/

public void backup(OutputStream output, String dbname) {

String command = "cmd /c " + mysqlBinPath + "mysqldump -u" + username

+ " -p" + password + " --set-charset=utf8 " + dbname

PrintWriter p = null

BufferedReader reader = null

try {

p = new PrintWriter(new OutputStreamWriter(output, "utf8"))

Process process = Runtime.getRuntime().exec(command)

InputStreamReader inputStreamReader = new InputStreamReader(process

.getInputStream(), "utf8")

reader = new BufferedReader(inputStreamReader)

String line = null

while ((line = reader.readLine()) != null) {

p.println(line)

}

p.flush()

} catch (UnsupportedEncodingException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

} finally {

try {

if (reader != null) {

reader.close()

}

if (p != null) {

p.close()

}

} catch (IOException e) {

e.printStackTrace()

}

}

}

/**

* 备份数据库,如果指定路径的文件不存在会自动生成

*

* @param dest

*备份文件的路径

* @param dbname

*要备份的数据库

*/

public void backup(String dest, String dbname) {

try {

OutputStream out = new FileOutputStream(dest)

backup(out, dbname)

} catch (FileNotFoundException e) {

e.printStackTrace()

}

}

/**

* 恢复数据库

*

* @param input

*输入流

* @param dbname

*数据库名

*/

public void restore(InputStream input, String dbname) {

String command = "cmd /c " + mysqlBinPath + "mysql -u" + username

+ " -p" + password + " " + dbname

try {

Process process = Runtime.getRuntime().exec(command)

OutputStream out = process.getOutputStream()

String line = null

String outStr = null

StringBuffer sb = new StringBuffer("")

BufferedReader br = new BufferedReader(new InputStreamReader(input,

"utf8"))

while ((line = br.readLine()) != null) {

sb.append(line + "/r/n")

}

outStr = sb.toString()

OutputStreamWriter writer = new OutputStreamWriter(out, "utf8")

writer.write(outStr)

writer.flush()

out.close()

br.close()

writer.close()

} catch (UnsupportedEncodingException e) {

e.printStackTrace()

} catch (IOException e) {

e.printStackTrace()

}

}

/**

* 恢复数据库

*

* @param dest

*备份文件的路径

* @param dbname

*数据库名

*/

public void restore(String dest, String dbname) {

try {

InputStream input = new FileInputStream(dest)

restore(input, dbname)

} catch (FileNotFoundException e) {

e.printStackTrace()

}

}

public static void main(String[] args) {

Configuration config = HibernateSessionFactory.getConfiguration()

String binPath = config.getProperty("mysql.binpath")

String userName = config.getProperty("connection.username")

String pwd = config.getProperty("connection.password")

DatabaseBackup bak = new DatabaseBackup(binPath, userName, pwd)

bak.backup("c:/ttt.sql", "ttt")

bak.restore("c:/ttt.sql", "ttt")

}

}

最后的main方法只是一个简单的使用方法的示例代码。

本人所做的项目是使用了hibernate的,而这里需要提供MySQL的bin路径和用户名、密码,而hibernate.cfg.xml中本身就是需要配置数据库的用户名和密码,所以我把MySQL的bin路径也直接配置到了这个文件里面,也不需要创建专门的配置文件,不需要写读取配置文件的接口了。

如果不明白,可以去看hibernate.cfg.xml的说明,里面是可以配置其他的property的


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/sjk/9883192.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2023-05-03
下一篇 2023-05-03

发表评论

登录后才能评论

评论列表(0条)

保存