C# 数据库备份还原
时间: 2023-12-20 18:05:23 浏览: 146
以下是C#中数据库备份还原的方法:
1. 数据库备份:
```csharp
string backupPath = @"保存路径\dbName.bak";
string backupQuery = string.Format("backup database {0} to disk='{1}'", databaseName, backupPath);
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(backupQuery, connection);
command.ExecuteNonQuery();
}
Console.WriteLine("数据库备份成功!");
}
catch (Exception ex)
{
Console.WriteLine("数据库备份失败:" + ex.Message);
}
```
2. 数据库还原:
```csharp
string backupPath = @"保存路径\dbName.bak";
string restoreQuery = string.Format("use master; restore database {0} from disk='{1}'", databaseName, backupPath);
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
SqlCommand command = new SqlCommand(restoreQuery, connection);
command.ExecuteNonQuery();
}
Console.WriteLine("数据库还原成功!");
}
catch (Exception ex)
{
Console.WriteLine("数据库还原失败:" + ex.Message);
}
```
阅读全文