且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何通过C#代码还原SQL Server数据库

更新时间:2022-11-25 10:51:03

您DB连接是最有可能你正试图恢复数据库。因此,有一个数据库共享锁可以防止您的数据库的恢复



试试这个

  SQL = @使用母版BACKUP DATABASE MYDATABASE TO DISK ='D:\MyDATA.BAK'; 

或更改连接的详细信息使用主DB


I try to restore the database like this:

SQL = @"RESTORE DATABASE MyDataBase TO DISK='d:\MyDATA.BAK'";
                Cmd = new SqlCommand(SQL, Conn);
                Cmd.ExecuteNonQuery();
                Cmd.Dispose();

but I always get error:

Msg 3102, Level 16, State 1, Line 7
RESTORE cannot process database 'MyDataBase ' because it is in use by this session. It is recommended that the master database be used when performing this operation.
Msg 3013, Level 16, State 1, Line 7
RESTORE DATABASE is terminating abnormally.

Your DB connection is most likely to the database you're trying to restore. So there is a DB shared lock which prevents the restore of your db

Try this

SQL = @"USE master BACKUP DATABASE MyDataBase TO DISK='d:\MyDATA.BAK'";

Or change the connection details to use master DB