gpt4 book ai didi

c# - 使用 C# 恢复 SQL 数据库

转载 作者:太空宇宙 更新时间:2023-11-03 14:01:25 25 4
gpt4 key购买 nike

我正在尝试使用 C# 代码恢复 sql 数据库。备份工作正常。但是当恢复数据库时它给了我一个错误。我正在使用 Microsoft.SqlServer.Management.Smo; 进行此操作。错误是{“System.Data.SqlClient.SqlError:RESTORE 无法处理数据库‘TempDb’,因为它正在被该 session 使用。建议在执行此操作时使用 master 数据库。"

在几篇文章中,它说将数据库设置为 master。我也试过了。但它给了我同样的错误。连接字符串:connectionString = @"server=(local);Initial Catalog=Master;Integrated Security=True;";

我的代码如下:

openFileDialog1.ShowDialog();
string databaseName = "TempDb";
Restore sqlRestore = new Restore();

BackupDeviceItem deviceItem = new BackupDeviceItem(openFileDialog1.FileName, DeviceType.File);
sqlRestore.Devices.Add(deviceItem);
sqlRestore.Database = databaseName;

DataConnection dataConnection = new DataConnection();
ServerConnection connection = new ServerConnection(dataConnection.DataBaseConnection);
Server sqlServer = new Server(connection);

Database db = sqlServer.Databases[databaseName];
sqlRestore.Action = RestoreActionType.Database;
String dataFileLocation = db.FileGroups[0].Files[0].FileName;
String logFileLocation = db.LogFiles[0].FileName;
db = sqlServer.Databases[databaseName];
RelocateFile rf = new RelocateFile(databaseName, dataFileLocation);


sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName, dataFileLocation));
sqlRestore.RelocateFiles.Add(new RelocateFile(databaseName + "_log", logFileLocation));
sqlRestore.ReplaceDatabase = true;
sqlRestore.Complete += new ServerMessageEventHandler(sqlRestore_Complete);
sqlRestore.PercentCompleteNotification = 10;
sqlRestore.PercentComplete += new PercentCompleteEventHandler(sqlRestore_PercentComplete);
sqlRestore.SqlRestore(sqlServer);
db = sqlServer.Databases[databaseName];
db.SetOnline();
sqlServer.Refresh();

最佳答案

this code For Restore Database,Please Type Code In C#:

SqlConnection ObjConnection=new SqlConnection("Your Connection String");
ObjConnection.Open();
SqlCommand ObjCommand = new SqlCommand();
ObjCommand.Connection = ObjConnection;
ObjCommand.CommandText = "Use Master ALTER DATABASE YourDatabaseName SET OFFLINE WITH ROLLBACK IMMEDIATE " +
"Restore Database YourDatabaseName From Disk='" + LblPath.Text + "'" +
" ALTER DATABASE YourDatabaseName SET ONLINE WITH ROLLBACK IMMEDIATE";
ObjCommand.CommandType = CommandType.Text;
ObjCommand.ExecuteNonQuery();
Help:LblPath.Text is a Label Control Contain Path Backup Database You!
Mojtaba From IRAN

关于c# - 使用 C# 恢复 SQL 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10639903/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com