使sql连接打开很长时间 [英] Having sql connection open for a long time

查看:218
本文介绍了使sql连接打开很长时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个生成站点地图的程序。为了避免重复,我使用MSSQL服务器来存储找到的链接。在这个过程中它可以读取和写入数以百万计的链接,并且读取和写入的过程之间可能有很少的差距(我的意思是每次访问数据库之间的时间非常小)。



我想知道如果我可以在程序启动时打开连接,并在结束时关闭它。请考虑创建一些网站地图可能需要几天才能完成。



顺便说一句,我在本地使用sql server。

解决方案

您的问题的答案是连接池功能。



确实存在一个特定的工作模式



<$ p $

p> using(SqlConnection con = new SqlConnection(.....))
{
...使用这里的数据库....
}

使用语句确保在开头创建的对象被关闭并且放置在关闭大括号。



这并不意味着您不能尝试优化您的代码。例如,您可以将一些站点地图集合在一起,并在一次写入,但通常最好遵循一个简单的工作模式,尽快完成工作,担心以后优化。


I'm writing a program that generates Sitemaps. To avoid duplicates I'm using MSSQL Server to store links that are found. during this process It may read and write millions of links and the process of reading and writing may have very little gaps between them (I mean the time between each access to database is very tiny).

I want to know If I can open the connection when the program starts and close it at the end. please consider that creating some sitemaps may take days to finish. Or is it wise to open and close connection each time I want to access the db?

By the way, I'm using sql server locally.

解决方案

The answer to your question is the Connection Pooling feature.

It is always preferable to open the connection just when needed, access your data, close and dispose the connection immediately

Indeed a specific work pattern exists

using(SqlConnection con = new SqlConnection(.....))
{
   ... do your work with the database here ....
}

The using statement ensures that the object created at the opening is closed and disposed at the closing braces. Even if an Exception occurs in database code.

This doesn't mean that you cannot try to optimize your code. For example you could gather a few of sitemaps together and write them in just one shot, but usually it is best to follow a simple work pattern, finish the work as soon as possible and worry for optimization later.

这篇关于使sql连接打开很长时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆