Deleting database from C#

后端 未结 7 920
感情败类
感情败类 2020-12-16 00:01

I have an MDF file that I\'m attaching to my local SQL server during testing with MSTEST and I don\'t want to have to go delete those temporary databases by hand after I\'ve

7条回答
  •  天命终不由人
    2020-12-16 00:22

    Take a look at the SMO (SQL Server Management Objects) .NET wrappers.

    These allow you to manage all aspects of SQL Server from code, including deleting of databases.

    The database object has a Drop method.

    The code below is to illustrate how you could use the object model, though I have not tested it:

    var server = new Server(serverName); // Can use overload that specifies 
    
    foreach (Database db in server.Databases)
    {
         if (db.Name.ToLower().Contains(testDatabaseIdentifier))
         {
              databasesToDelete.Add(db.Name);
         }
    }
    databasesToDelete.ForEach(x =>
    {
         Database db = new Database(server, x);
         db.Refresh();
         db.Drop();
    });
    

提交回复
热议问题