您可以使用 SQL Server 备份向导或使用 SQL Server Backup Database 语句进行数据库备份
SQL Server 管理对象 (SMO) 是一组对象,旨在对管理 Microsoft SQL Server 的各个方面进行编程。
要使用 C# 进行数据库备份,您必须在应用程序中添加以下引用-
Microsoft.SqlServer.ConnectionInfo
Microsoft.SqlServer.Management.Sdk.Sfc
Microsoft.SqlServer.Smo
Microsoft.SqlServer.SmoExtended
Microsoft.SqlServer.SqlEnum
在您的 .CS 文件中,您必须使用以下命名空间-
using Microsoft.SqlServer.Management.Smo;
using Microsoft.SqlServer.Management.Common;
使用上述命名空间后,编写以下代码进行数据库备份-
public void BackupDatabase(string databaseName, string userName, string password, string serverName, string destinationPath)
{
//Define a Backup object variable.
Backup sqlBackup = new Backup();
//Specify the type of backup, the description, the name, and the database to be backed up.
sqlBackup.Action = BackupActionType.Database;
sqlBackup.BackupSetDescription = "BackUp of:" + databaseName + "on" + DateTime.Now.ToShortDateString();
sqlBackup.BackupSetName = "FullBackUp";
sqlBackup.Database = databaseName;
//Declare a BackupDeviceItem
BackupDeviceItem deviceItem = new BackupDeviceItem(destinationPath + "FullBackUp.bak", DeviceType.File);
//Define Server connection
ServerConnection connection = new ServerConnection(serverName, userName, password);
//To Avoid TimeOut Exception
Server sqlServer = new Server(connection);
sqlServer.ConnectionContext.StatementTimeout = 60 * 60;
Database db = sqlServer.Databases[databaseName];
sqlBackup.Initialize = true;
sqlBackup.Checksum = true;
sqlBackup.ContinueAfterError = true;
//Add the device to the Backup object.
sqlBackup.Devices.Add(deviceItem);
//Set the Incremental property to False to specify that this is a full database backup.
sqlBackup.Incremental = false;
sqlBackup.ExpirationDate = DateTime.Now.AddDays(3);
//Specify that the log must be truncated after the backup is complete.
sqlBackup.LogTruncation = BackupTruncateLogType.Truncate;
sqlBackup.FormatMedia = false;
//Run SqlBackup to perform the full database backup on the instance of SQL Server.
sqlBackup.SqlBackup(sqlServer);
//Remove the backup device from the Backup object.
sqlBackup.Devices.Remove(deviceItem);
}
使用 SQL Server 的生成脚本推荐
右键单击数据库;任务 -> 生成脚本
- 选择您的表格,点击下一步
- 点击高级按钮
- 查找要编写脚本的数据类型 - 选择架构和数据。
- 然后您可以选择保存到文件,或放入新的查询窗口。
- 为项目符号 2 中选择的所有表数据生成 CREATE 和 INSERT 语句。