繁体   English   中英

如何通过C#以编程方式在不使用.mdf或.ldf文件的情况下将.bak文件还原到新服务器?

[英]How can I restore a .bak file to a new server without using the .mdf or .ldf files, programmatically with C#?

一些入门信息:

  1. 我正在使用SQL Server Express 2014
  2. 我正在使用C#
  3. 我无法使用SMO功能来完成以下任务

我正在尝试将从计算机A获得的.bak文件还原到计算机B。我想以编程方式使用C#,但不使用SMO功能。

在SSMS(SQL Server Management Studio)中,我可以仅使用.bak文件来手动还原数据库。 我希望能够使用C#运行程序进行相同的操作。

只要拥有.mdf和.ldf文件,我就可以还原.bak文件,但如果没有它们,则无法恢复。 在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文件来还原备份? 预先感谢您抽出宝贵的时间对此进行研究。

如@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 Files \\ Microsoft SQL Server \\ MSSQL12.ANTSQLSERVER \\ MSSQL \\ DATA \\)路径是创建.mdf和.ldf文件的默认位置。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM