搜尋
首頁資料庫mysql教程备份恢复数据库

备份恢复数据库

Jun 07, 2016 pm 03:36 PM
備份恢復資料庫系統

每个系统都应该有数据库的备份和还原功能,以防各种情况下的数据库损坏造成不可挽回的损失。这个功能挺简单,但在代码实现过程中也多多少少遇到了些问题,我把错误都总结了出来,供大家参考学习。 下面先给出正确的代码实现: Imports System.Data.SqlClient

         每个系统都应该有数据库的备份和还原功能,以防各种情况下的数据库损坏造成不可挽回的损失。这个功能挺简单,但在代码实现过程中也多多少少遇到了些问题,我把错误都总结了出来,供大家参考学习。

下面先给出正确的代码实现:

Imports System.Data.SqlClient

Public Class Form1

    '备份数据库 
    'BACKUP DATABASE Test TO DISK='' WITH Format   sql语句

    Private Sub btnBackup_Click(sender As Object, e As EventArgs) Handles btnBackup.Click

        Dim conn As SqlConnection
        conn = New SqlConnection("Data Source=.;Initial Catalog=test3;User ID=sa;Password=123456")
        Dim cmd As SqlCommand
        Dim path As String

        '选择备份路径
        FolderBrowserDialog1.ShowDialog()
        path = FolderBrowserDialog1.SelectedPath
        If path = Nothing Then
            MessageBox.Show("文件名不能为空", "系统提示")
            Exit Sub
        End If
        '执行sql命令语句,备份数据库
        cmd = New SqlCommand("BACKUP DATABASE test3 TO DISK='" & path & "\backup' WITH format,BACKUP LOG WITH NORECOVERY", conn)
        conn.Open()
        Try
            cmd.ExecuteNonQuery()
        Catch ex As Exception
            MsgBox(ex.Message, MsgBoxStyle.OkOnly, "系统提示")
            Exit Sub
        End Try
        MsgBox("备份成功")
        conn.Close()

    End Sub

    '还原数据库
    Private Sub btnRecovery_Click(sender As Object, e As EventArgs) Handles btnRecovery.Click
        If MsgBox("真的要还原吗?数据会恢复到最近备份的数据!", MsgBoxStyle.YesNo, "系统提示") = MsgBoxResult.Yes Then

            Dim cn As New SqlConnection
            Dim cn1 As New SqlConnection
            Dim mydr As SqlDataReader
            Dim str As String
            Dim tmpConnectionString As String = "Data Source=.;Initial Catalog=test3;User ID=sa;Password=123456;pooling=false"
            Dim all As String

            '获取当前文件名筛选器字符
            Me.OpenFileDialog1.Filter = "所有文件(*.*)|*.*|备份文件(*.bak)|*.bak"
            Me.OpenFileDialog1.ShowDialog()
            all = OpenFileDialog1.FileName
            If all = Nothing Then
                MessageBox.Show("文件名不能为空", "系统提示")
                Exit Sub
            End If
            cn.ConnectionString = tmpConnectionString
            cn1.ConnectionString = tmpConnectionString
            cn.Open()
            cn1.Open()

            '查询与数据库有关的进程
            Dim cm As SqlCommand = New SqlCommand("use master select spid from master..sysprocesses where dbid=db_id('test3')", cn)
            mydr = cm.ExecuteReader()
            Dim cm1 As SqlCommand = New SqlCommand()
            cm1.Connection = cn1
            While (mydr.Read())
                '杀死进程
                str = "kill " & mydr("spid").ToString()
                cm1.CommandText = str
                cm1.CommandType = CommandType.Text
                Application.DoEvents()
                cm1.ExecuteNonQuery()
            End While
            mydr.Close()

            '使要还原的数据库脱机
            cm = New SqlCommand("ALTER DATABASE test3 SET OFFLINE WITH ROLLBACK IMMEDIATE", cn)
            cm.ExecuteNonQuery()

            '恢复备份
            cm = New SqlCommand("RESTORE DATABASE test3 FROM DISK='" & all & "' WITH REPLACE", cn)
            cm.ExecuteNonQuery()

            '使要还原的数据库联机
            cm = New SqlCommand("ALTER DATABASE test3 SET ONLINE WITH ROLLBACK IMMEDIATE", cn)
            cm.ExecuteNonQuery()

            MsgBox("恢复成功,软件自动关闭,请重新启动本系统!")

            '关闭数据库连接
            cn.Close()
            cn1.Close()
            Me.Close()
        Else
            Exit Sub
        End If
    End Sub
End Class


 错误代码一:

select spid from test3..sysprocesses where dbid=db_id('test3')

错误描述:

 备份恢复数据库

解决方法:

在sql语句前添加use master 即

use master select spid from master..sysprocesses where dbid=db_id('test3')

User master表示在master数据库执行该语句,spid指当前用户进程的会话 ID,master是系统数据库,它里面有很多对象,每个对象都有自己的所有者.如果没有指明所有者,系统就默认dbo为对象的所有者.一个对象完整的表达式为:数据库名.所有者.对象, 比如:master.dbo.sysobjects。杀进程前当然要先找出当前该数据库所有的进程了。


错误二:

直接用SQL语句还原数据库。

错误描述:

备份恢复数据库 

解决方法:

方法一:

在还原之前先将该数据库脱机,恢复之后再联机。前后加上两条sql语句即可。 

ALTER DATABASE [datebase] SET OFFLINE WITH ROLLBACK IMMEDIATE

ALTER  DATABASE  [ datebase] SET ONLINE  

方法二:

(该方法采取限制访问数据库的方式,因为实际中我们经常多用户访问,所以符合情况时再考虑这种解决方法吧。)

在还原的时候还有其他进程连在上面,导致无法获得独占造成的,可以使用数据库的单用户模式,设置方式:选中要还原的数据库-->属性-->选项-->限制访问,该值从MULTI_USER修改为SINGLE_USER。

以下是GUI的模式,语句比较简单 

USE MASTER 

GO 

ALTER DATABASEeol_tcgroup SET SINGLE_USER WITH ROLLBACK IMMEDIATE; 

GO 


陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
在MySQL中使用視圖的局限性是什麼?在MySQL中使用視圖的局限性是什麼?May 14, 2025 am 12:10 AM

mysqlviewshavelimitations:1)他們不使用Supportallsqloperations,限制DatamanipulationThroughViewSwithJoinsOrsubqueries.2)他們canimpactperformance,尤其是withcomplexcomplexclexeriesorlargedatasets.3)

確保您的MySQL數據庫:添加用戶並授予特權確保您的MySQL數據庫:添加用戶並授予特權May 14, 2025 am 12:09 AM

porthusermanagementinmysqliscialforenhancingsEcurityAndsingsmenting效率databaseoperation.1)usecReateusertoAddusers,指定connectionsourcewith@'localhost'or@'%'。

哪些因素會影響我可以在MySQL中使用的觸發器數量?哪些因素會影響我可以在MySQL中使用的觸發器數量?May 14, 2025 am 12:08 AM

mysqldoes notimposeahardlimitontriggers,butacticalfactorsdeterminetheireffactective:1)serverConfiguration impactactStriggerGermanagement; 2)複雜的TriggerSincreaseSySystemsystem load; 3)largertablesslowtriggerperfermance; 4)highConconcConcrencerCancancancancanceTigrignecentign; 5); 5)

mysql:存儲斑點安全嗎?mysql:存儲斑點安全嗎?May 14, 2025 am 12:07 AM

Yes,it'ssafetostoreBLOBdatainMySQL,butconsiderthesefactors:1)StorageSpace:BLOBscanconsumesignificantspace,potentiallyincreasingcostsandslowingperformance.2)Performance:LargerrowsizesduetoBLOBsmayslowdownqueries.3)BackupandRecovery:Theseprocessescanbe

mySQL:通過PHP Web界面添加用戶mySQL:通過PHP Web界面添加用戶May 14, 2025 am 12:04 AM

通過PHP網頁界面添加MySQL用戶可以使用MySQLi擴展。步驟如下:1.連接MySQL數據庫,使用MySQLi擴展。 2.創建用戶,使用CREATEUSER語句,並使用PASSWORD()函數加密密碼。 3.防止SQL注入,使用mysqli_real_escape_string()函數處理用戶輸入。 4.為新用戶分配權限,使用GRANT語句。

mysql:blob和其他無-SQL存儲,有什麼區別?mysql:blob和其他無-SQL存儲,有什麼區別?May 13, 2025 am 12:14 AM

mysql'sblobissuitableForStoringBinaryDataWithInareLationalDatabase,而ilenosqloptionslikemongodb,redis和calablesolutionsolutionsolutionsoluntionsoluntionsolundortionsolunsonstructureddata.blobobobissimplobisslowdeperformberbutslowderformandperformancewithlararengedata;

mySQL添加用戶:語法,選項和安全性最佳實踐mySQL添加用戶:語法,選項和安全性最佳實踐May 13, 2025 am 12:12 AM

toaddauserinmysql,使用:createUser'username'@'host'Indessify'password'; there'showtodoitsecurely:1)choosethehostcarecarefullytocon trolaccess.2)setResourcelimitswithoptionslikemax_queries_per_hour.3)usestrong,iniquepasswords.4)Enforcessl/tlsconnectionswith

MySQL:如何避免字符串數據類型常見錯誤?MySQL:如何避免字符串數據類型常見錯誤?May 13, 2025 am 12:09 AM

toAvoidCommonMistakeswithStringDatatatPesInMysQl,CloseStringTypenuances,chosethirtightType,andManageEngencodingAndCollat​​ionsEttingSefectery.1)usecharforfixed lengengtrings,varchar forvariable-varchar forbariaible length,andtext/blobforlargerdataa.2 seterters seterters seterters

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具