如何通过代码在C#中备份数据库?

发布于 2024-10-21 20:37:00 字数 85 浏览 3 评论 0原文

例如,我删除了数据库上表上的一条记录,我的数据库是MS Aaccess。有什么备份机制可以参考吗?这样,当我需要回滚数据库时,我只需从代码中快速恢复它即可。

For example, I deleted a record on a table on the database and my database is MS Aaccess. Any backup mechanisms that I can refer to? So that when I need a rollback of the database I just restore it quickly from code.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

抚你发端 2024-10-28 20:37:00

MS Access 是基于文件的数据库,对吗?根据我的理解,这意味着,当连接关闭并且文件未使用时,您可以将该文件复制到另一个位置。

这里我假设应用程序在文件系统上具有这样的权限。

另外,我同意Morten Martner的回答,如果数据库类型是MS SQL Server,那么你肯定需要使用SMO库。

MS Access is the file based database, right? in my understanding, that means, when the connection is closed and the file is not in use, you can copy that file to another location.

Here I assume the application has such privileges on the file system.

Also, I agree with Morten Martner's answer, if the database type is MS SQL Server, then you will definitely need SMO library use.

烟─花易冷 2024-10-28 20:37:00

我使用以下代码来备份 SQL Server 数据库:

using System;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Text;

namespace Codeworks.SqlServer.BackupDatabase
{
    public class BackupCore
    {
        public static void Execute( string instance, string database, string outputFile )
        {
            BackupDeviceItem bdi = new BackupDeviceItem( outputFile, DeviceType.File );
            Backup bu = new Backup();
            bu.Database = database;
            bu.Devices.Add( bdi );
            bu.Initialize = true;

            // add percent complete and complete event handlers
            bu.PercentComplete += new PercentCompleteEventHandler(Backup_PercentComplete);
            bu.Complete +=new ServerMessageEventHandler(Backup_Complete);

            Server server = new Server( instance );
            bu.SqlBackup( server );
        }

        protected static void Backup_PercentComplete( object sender, PercentCompleteEventArgs e )
        {
            // Console.WriteLine( e.Percent + "% processed." );
        }

        protected static void Backup_Complete( object sender, ServerMessageEventArgs e )
        {
            Console.WriteLine( e.ToString() );
        }
    }
}

您需要 MS 的管理库才能获得正确的 SQL Server 版本,但这些都可以下载。

I'm using the following code to backup SQL server databases:

using System;
using System.Collections.Generic;
using System.Data;
using System.Collections;
using Microsoft.SqlServer.Management.Common;
using Microsoft.SqlServer.Management.Smo;
using System.Text;

namespace Codeworks.SqlServer.BackupDatabase
{
    public class BackupCore
    {
        public static void Execute( string instance, string database, string outputFile )
        {
            BackupDeviceItem bdi = new BackupDeviceItem( outputFile, DeviceType.File );
            Backup bu = new Backup();
            bu.Database = database;
            bu.Devices.Add( bdi );
            bu.Initialize = true;

            // add percent complete and complete event handlers
            bu.PercentComplete += new PercentCompleteEventHandler(Backup_PercentComplete);
            bu.Complete +=new ServerMessageEventHandler(Backup_Complete);

            Server server = new Server( instance );
            bu.SqlBackup( server );
        }

        protected static void Backup_PercentComplete( object sender, PercentCompleteEventArgs e )
        {
            // Console.WriteLine( e.Percent + "% processed." );
        }

        protected static void Backup_Complete( object sender, ServerMessageEventArgs e )
        {
            Console.WriteLine( e.ToString() );
        }
    }
}

You'll need the management libraries from MS for the correct SQL server version, but those are available for download.

寻梦旅人 2024-10-28 20:37:00

如果您是数据库的单个用户,则只需关闭连接并使用文件系统复制它即可。

如果有多个用户,那么您应该使用不同的方法。如果您确实有可用的 Access,则有一个未记录的命令可以将表备份为 Jet/ACE 文件:

  Application.SaveAsText 6, vbNullString, strTargetMDB 

现在,由于这只能在 Access UI 中打开数据库的情况下完成,因此需要自动化 Access 并在当前数据库。下面是在 Access 中运行的实现:

  Public Function CreateBackup(strMDBName As String, strBackupPath As String, _
    Optional bolCompact As Boolean = False) As Boolean
  On Error GoTo errHandler
    Dim objAccess As Object
    Dim strBackupMDB As String
    Dim strCompactMDB As String

    If Len(Dir(strBackupPath & "\*.*")) = 0 Then ' alternative: use File System Object for this
       MkDir strBackupPath
    End If

    Set objAccess = New Access.Application
    objAccess.Application.OpenCurrentDatabase strMDBName
    strBackupMDB = "Backup" & Format(Now(), "YYYYMMDDhhnnss") & ".mdb"
    Debug.Print strBackupPath & "\" & strBackupMDB
    objAccess.Application.SaveAsText 6, vbNullString, strBackupPath & "\" & strBackupMDB
    objAccess.Application.Quit
    Set objAccess = Nothing

    If bolCompact Then
       strCompactMDB = strBackupPath & "\" & "c_" & strBackupMDB
       Name strBackupPath & "\" & strBackupMDB As strCompactMDB
       DBEngine.CompactDatabase strCompactMDB, strBackupPath & "\" & strBackupMDB
       Kill strCompactMDB
    End If

    CreateBackup = (Len(Dir(strBackupPath & "\" & strBackupMDB)) > 0)

  exitRoutine:
    If Not (objAccess Is Nothing) Then
       On Error Resume Next
       objAccess.Application.Quit
       On Error GoTo 0
       Set objAccess = Nothing
    End If
    Exit Function

  errHandler:
    Select Case Err.Number
      Case 75 ' Path/File access error -- tried to MkDir a folder that already exists
        Resume Next
      Case Else
        MsgBox Err.Number & ": " & Err.Description, vbExclamation, "Error in CreateBackup()"
        Resume exitRoutine
    End Select
  End Function

要从 C# 运行该实现,您必须自动化 Access,并且您可能不希望依赖于 Access。

由于我只在 Access 中工作,这就是我使用的方法,所以我从未编写过更复杂的方法。

如果您对数据库具有独占访问权限,则可以使用 JRO CompactDatabase 命令压缩为新文件名,但如果您具有独占访问权限,则还可以使用文件系统。

因此,基本上,您可以选择如何将数据表导出到备份数据库。您可以使用 DoCmd.TransferDatabase 复制所有数据表,然后复制关系,或者您可以创建一个空模板数据库并将每个表中的数据依次附加到模板的副本中(按顺序不会当然,违反了 RI)。

这些对我来说听起来都没什么意思,这就是我使用 SaveAsText 方法的原因!但如果我不运行 Access,其他两个替代方案就值得做。

If you're a single user of your database, you just need to close your connection and copy it with the file system.

If there are multiple users, then you should use a different method. If you actually have Access available, there's an undocumented command that will make a backup of the tables a Jet/ACE file:

  Application.SaveAsText 6, vbNullString, strTargetMDB 

Now, since this can only be done with the database open in the Access UI, it requires automating Access and operating on the CurrentDB. Here's an implementation that runs within Access:

  Public Function CreateBackup(strMDBName As String, strBackupPath As String, _
    Optional bolCompact As Boolean = False) As Boolean
  On Error GoTo errHandler
    Dim objAccess As Object
    Dim strBackupMDB As String
    Dim strCompactMDB As String

    If Len(Dir(strBackupPath & "\*.*")) = 0 Then ' alternative: use File System Object for this
       MkDir strBackupPath
    End If

    Set objAccess = New Access.Application
    objAccess.Application.OpenCurrentDatabase strMDBName
    strBackupMDB = "Backup" & Format(Now(), "YYYYMMDDhhnnss") & ".mdb"
    Debug.Print strBackupPath & "\" & strBackupMDB
    objAccess.Application.SaveAsText 6, vbNullString, strBackupPath & "\" & strBackupMDB
    objAccess.Application.Quit
    Set objAccess = Nothing

    If bolCompact Then
       strCompactMDB = strBackupPath & "\" & "c_" & strBackupMDB
       Name strBackupPath & "\" & strBackupMDB As strCompactMDB
       DBEngine.CompactDatabase strCompactMDB, strBackupPath & "\" & strBackupMDB
       Kill strCompactMDB
    End If

    CreateBackup = (Len(Dir(strBackupPath & "\" & strBackupMDB)) > 0)

  exitRoutine:
    If Not (objAccess Is Nothing) Then
       On Error Resume Next
       objAccess.Application.Quit
       On Error GoTo 0
       Set objAccess = Nothing
    End If
    Exit Function

  errHandler:
    Select Case Err.Number
      Case 75 ' Path/File access error -- tried to MkDir a folder that already exists
        Resume Next
      Case Else
        MsgBox Err.Number & ": " & Err.Description, vbExclamation, "Error in CreateBackup()"
        Resume exitRoutine
    End Select
  End Function

To run that from C# you'd have to automate Access, and you likely don't want a dependency on Access.

Since I work in Access exclusively, that's the method I use, so I've never programmed the more complicated methods.

If you have exclusive access to the database, you could use JRO CompactDatabase command to compact to a new filename, but if you have exclusive access, you can also use the file system.

So, basically, you've got choices about how to export the data tables to a backup database. You could use DoCmd.TransferDatabase to copy all the data tables, and then copy the relationships, or you could create an empty template database and append the data from each table in turn to a copy of the template (in an order that won't violate RI, of course).

Neither of those sounds anything but messy to me, and that's why I use the SaveAsText method! But if I wasn't running Access, the other two alternatives would be worth doing.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文