Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Deleting database from C#

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();
});
like image 698
khr055 Avatar asked Mar 02 '11 16:03

khr055


People also ask

Can you delete a database using the command?

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.

Which command is used to delete a database?

The DROP DATABASE command is used to delete an existing SQL database.

How do I delete an existing MySQL 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.


1 Answers

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);
like image 170
feO2x Avatar answered Sep 21 '22 11:09

feO2x