C# 数据库备份还原
时间: 2023-12-20 15:05:23 浏览: 40
以下是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);
}
```
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)