有一些信息要开始:
我正在尝试将从计算机A到计算机B的.bak文件还原到计算机B上。我想通过编程方式使用C#,但不使用SMO函数。
在SSMS ()中,我只需使用.bak文件即可手动恢复数据库。我希望能够使用C#运行同样的程序。
只要我有.bak和.ldf文件,我就能够恢复它们,但没有它们就不行了。在SSMS中手动执行此操作似乎有效,因此我假设必须有一种使用C#的方法。以下是我所拥有的:
DBConnection connect1 = new DBConnection();
connect1.connectionString = "Data Source=" + textBox1.Text + "; Integrated Security=SSPI"; // textbox1 contains a user entered server name.
// Create a new database.
using (SqlConnection myConnection = new SqlConnection(connect1.connectionString))// set the connection to sql.
{
SqlCommand createDB = new SqlCommand("Create Database [" + dbName + "]", myConnection);
createDB.Connection.Open();
createDB.ExecuteNonQuery();
}
// Restore the data from the backup into the new database.
connect1 = new DBConnection();
connect1.connectionString = "Data Source=" + textBox1.Text + "; Initial Catalog=Master; Integrated Security=SSPI";
using (SqlConnection myConnection = new SqlConnection(connect1.connectionString))// set the connection to sql.
{
//SqlCommand createDB = new SqlCommand("Restore Database [" + dbName + "] FROM DISK = " + bakDirctory + " "
// + "WITH MOVE '" + oldDBName + "' TO '" + mdfDirectory + "', "
// + "MOVE '" + oldDBName + "_log' TO '" + ldfDirectory + "', "
// + "REPLACE", myConnection);
// oldDBName contains what the name of the database was when the .bak file was created.
SqlCommand createDB = new SqlCommand("Restore Database [" + dbName + "] FROM DISK = " + bakDirectory, myConnection);
createDB.Connection.Open();
createDB.ExecuteNonQuery();
}代码片段的注释部分可以工作,但需要使用.mdf和.ldf文件。下面的部分只使用.bak文件,但是当我试图运行该代码时,我得到了一个未处理的异常:
备份集保存现有“dbname”数据库以外的数据库的备份
我认为这是因为新创建的数据库的数据库结构与.bak文件中的数据库结构不匹配。(如果我错了,请纠正我)。是否有一种仅使用.bak文件恢复备份的方法?提前感谢您抽出时间来看这个。
发布于 2017-06-23 20:51:15
正如@DanGuzman所指出的,没有必要事先创建一个新的数据库。
按照(@ScottChamberlain)注释中的说明,我能够找到恢复数据库所需的脚本,而无需使用.mdf或.ldf文件。确切的脚本是:
SqlCommand createDB = new SqlCommand("RESTORE DATABASE [" + dbName + "] FROM DISK = N'" + bakDirectory + "' " +
"WITH FILE = 2, MOVE N'" + oldDBName + "' TO N'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.ANTSQLSERVER\\MSSQL\\DATA\\" + dbName + ".mdf', " +
"MOVE N'" + oldDBName + "_log' TO N'C:\\Program Files\\Microsoft SQL Server\\MSSQL12.ANTSQLSERVER\\MSSQL\\DATA\\" + dbName + "_log.ldf', NOUNLOAD, STATS = 5", myConnection);(C:\Program \Microsoft\MSSQL12.ANTSQLSERVER\MSSQL\DATA)路径是创建.mdf和.ldf文件的默认位置。
https://stackoverflow.com/questions/44729192
复制相似问题