Deleting database from C#

后端 未结 7 852
感情败类
感情败类 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:27

    feO2x's answer works great but he didn't give code. The following works if you have your database connection string in your app.config.

    using System.Configuration;
    using System.Data.SqlClient;
    using Microsoft.SqlServer.Management.Common;
    public class Foo
    {
        public static void DropDatabase(string connectionName)
        {
            using (
                var sqlConnection =
                    new SqlConnection(
                        ConfigurationManager.ConnectionStrings[connectionName]
                        .ConnectionString))
            {
                var serverConnection = new ServerConnection(sqlConnection);
                var server = new Microsoft.SqlServer.Management.Smo.Server(
                                 serverConnection);
                server.KillDatabase(sqlConnection.Database);
            }
        }
    }
    

    You must reference System.Data, *System.Configuratio*n, Microsoft.SqlServer.ConnectionInfo, Microsoft.SqlServer.Management.Sdk.Sfc, and Microsoft.SqlServer.Management.Smo.

提交回复
热议问题