寻找可以让我在 C# 测试 (MSTest) 内备份 SQL Server 2005/2008/2008R2 数据库的代码
我在下面找到了一个起点,但我担心我可能会错过对 CreateDbBackup()
和 RestoreDbBackup()
的调用。我希望我可以在测试中编写和使用属性。这可能吗?如何?我正在使用 MSTest 库和 C# 4.0。
http://www.linglom.com/2008/01/12/how-to-backup-and-restore-database-on-microsoft-sql-server-2005/
internal void CreateDbBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = string.Format(@"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath);
con.Open();
cmd.ExecuteNonQuery();
}
}
internal void RestoreDbFromBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
con.Open();
// Make sure to get exclusive access to DB to avoid any errors
cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE";
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format(@"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath);
cmd.ExecuteNonQuery();
}
}
I have found a starting point below, but I worry that I can miss calls to CreateDbBackup()
and RestoreDbBackup()
. I was hoping that I could write and use an attribute on my tests. Is this possible? How? I am using MSTest library and C# 4.0.
http://www.linglom.com/2008/01/12/how-to-backup-and-restore-database-on-microsoft-sql-server-2005/
internal void CreateDbBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = string.Format(@"BACKUP DATABASE [MyDatabase] TO DISK = N'{0}' WITH INIT , NOUNLOAD , NOSKIP , STATS = 10, NOFORMAT", UtilityClassGeneral.DbBackupPath);
con.Open();
cmd.ExecuteNonQuery();
}
}
internal void RestoreDbFromBackup()
{
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["myConStr"].ConnectionString))
{
SqlCommand cmd = con.CreateCommand();
con.Open();
// Make sure to get exclusive access to DB to avoid any errors
cmd.CommandText = "USE MASTER ALTER DATABASE [MyDatabase] SET SINGLE_USER With ROLLBACK IMMEDIATE";
cmd.ExecuteNonQuery();
cmd.CommandText = string.Format(@"RESTORE DATABASE [MyDatabase] FROM DISK = N'{0}' WITH FILE = 1, NOUNLOAD , STATS = 10, RECOVERY , REPLACE", UtilityClassGeneral.DbBackupPath);
cmd.ExecuteNonQuery();
}
}
查看SQL Server 管理对象 (SMO)。您应该能够使用它来备份和恢复 SQL Server 数据库。
Have a look at SQL Server Management Objects (SMO). You should be able to use this to backup and restore SQL Server databases.