开发者

SMO Server connection not closed

开发者 https://www.devze.com 2023-02-21 21:06 出处:网络
I\'m writing a C# application that upgrades client machines from one application version to another. The first step is to create a backup of a SQL database. I\'m doing this using SMO and it works fin

I'm writing a C# application that upgrades client machines from one application version to another. The first step is to create a backup of a SQL database. I'm doing this using SMO and it works fine. Next I uninstall a windows service. Then I try to rename the database that I backed up, again, using SMO. This fails because it says it can't gain exclusive access to the database. When I look at the activity monitor, I can see that there are two connections to the database I'm trying to rename. One connection is the one I'm using to try to rename the database, the other is the one I used to backup the database. It's status is sleeping but I'm assuming this is why I can't get exclusive access to rename the database. I was kind of surprised to find the SMO objec开发者_运维问答ts didn't implement IDisposable. I tried setting my Server object reference to null incase garbage collection might help, but that didn't work. The connections stay there until I quit the application.

So I have a couple of questions

  1. How do I get rid of the first connection? I know it's possible because it happens when my application shuts down
  2. Can I put the database in single user mode using or force the rename in some other way using SMO?

Thanks


I got it to work if I turn off pooling in my connection string by adding Pooling=false. Then calling Disconnect on the ServerConnection:

ServerConnection svrConn = null;

try
{
    string connString = Cryptographer.Decrypt(ConfigurationManager.ConnectionStrings["CS"].ConnectionString);
    svrConn = new Microsoft.SqlServer.Management.Common.ServerConnection(new System.Data.SqlClient.SqlConnection(connString));
    Server server = new Microsoft.SqlServer.Management.Smo.Server(svrConn);
    Backup backup = new Microsoft.SqlServer.Management.Smo.Backup();

    ...

    backup.SqlBackup(server);
}
catch (Exception ex)
{
    ...
}
finally
{
    if (svrConn != null)
        svrConn.Disconnect();
}

I think server.ConnectionContext.Disconnect would also work, but haven't tried it.

0

精彩评论

暂无评论...
验证码 换一张
取 消