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 run the test set 50 times. (I've already done that and I don't like it >.<)
I'm look for a way to delete the database from the server after I'm done with the tests, during my TestCleanup
method. I just need a little guidance on what SQL statements I would use to do this.
EDIT (By Software Monkey, from OP's rejected edit to ODED's answer)
Here is the code which worked for me:
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();
});
To do delete a database you need the command 'DROP DATABASE'. The syntax is similar to creating a database. 'DROP DATABASE <name>;', where <name> is the name of the database you want to delete.
The DROP DATABASE command is used to delete an existing SQL database.
First, launch the MySQL workbench and log in to the MySQL Server. Second, right-click the database that you want to remove, for example, testdb2 and choose the Drop Schema... option. Third, MySQL Workbench displays a dialog to confirm the deletion.
Instead of using the Database
type to delete a database in TestCleanup, I would recommend to use the Microsoft.SqlServer.Management.Smo.Server.KillDatabase
method. In addition, this will close all existing SQL connections before the database is deleted. Thus your unit tests (or rather integration tests) might leave connections open and this will have no effect on the cleanup method.
var server = new Server(SqlServerName);
server.KillDatabase(DatabaseName);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With