如何在Windows服务中关闭数据库连接 [英] How to close database connection in windows service
本文介绍了如何在Windows服务中关闭数据库连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有备份sql数据库的Windows服务
它运行良好但是在任何数据库备份之后服务保持连接打开一段时间,这会在我备份许多数据库时减慢数据库的速度
有什么问题?
我尝试了什么:
I have a windows service for backup sql databases
it works good but after any database backup the service keep the connection open for along time which slowing down the database when I backup many databases
what is the problem?
What I have tried:
private void BackupSqlServerDB(string BackupPath, string DBName, string DBCon)
{
SqlConnection Con = new SqlConnection();
try
{
System.DateTime TheTime = DateTime.Now;
string fileName = DBName + ".bak";
BackupPath = Path.Combine(BackupPath, fileName);
if (System.IO.File.Exists(BackupPath))
System.IO.File.Delete(BackupPath);
if (System.IO.File.Exists(BackupPath + ".zip"))
System.IO.File.Delete(BackupPath + ".zip");
Con.ConnectionString = DBCon;
Con.Open();
SqlCommand Cmd = new SqlCommand();
Cmd.Connection = Con;
Cmd.CommandText = "BACKUP DATABASE " + DBName + " TO DISK ='" + BackupPath + "';";
Cmd.CommandTimeout = 360;
Cmd.ExecuteNonQuery();
Cmd.Dispose();
Con.Close();
Con.Dispose();
GC.Collect();
}
catch (Exception ex)
{
AddLog(ex.Message, "Preparing Sql Backup", true);
}
finally
{
Con.Close();
Con.Dispose();
GC.Collect();
}
}
推荐答案
您可以尝试使用:
SqlConnection.ClearAllPools();
您已经使用Con.Close和Con.Dispose进行此操作。只是打开连接不会减慢数据库的速度以进行任何其他操作。
You're already doing it with Con.Close and Con.Dispose. Just having the connection open will not slow down the database for any other operations.
这篇关于如何在Windows服务中关闭数据库连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文