25.4. Dropping a Database

As with most drop situations, this one is pretty straightforward. We start with our now familiar server and connection info and then set a reference to what database we're interested in:

private void btnDropDB_Click(object sender, EventArgs e)
{
    // Create the server and connect to it.
    ServerConnection cn = new ServerConnection();
    cn.LoginSecure = true;

    Server svr = new Server(cn);
    svr.ConnectionContext.Connect();

    Database db = svr.Databases["SMODatabase"];

Then just call the Drop() method and we're done:

db.Drop();

   txtResult.Text = "Database Dropped";

   cn.Disconnect();

}

NOTE

Note that we do not have any error trapping added here (there really isn't anything different than other error-trapping issues in your language of choice). You may run into some issues dropping the database if you still have connections open to that database elsewhere in this or other applications (such as Management Studio).

Get Professional SQL Server™ 2005 Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.