Home Database Mysql Tutorial 为什么要关闭数据库连接,可以不关闭吗?

为什么要关闭数据库连接,可以不关闭吗?

Jun 07, 2016 pm 03:10 PM
Why closure Can database illustrate connect

首先要说明的是连接数是有限制的: 代码如下: for ( int i = 0; i 10000; i++){ SqlConnection conn = new SqlConnection( @Data Source=.\SQLEXPRESS; AttachDbFilename= E:\DB\NORTHWND.mdf ; Integrated Security=True;Connect Timeout=30;User Instance

首先要说明的是连接数是有限制的:

代码如下:

<span>for</span> (<span>int</span> i = 0; i new SqlConnection(<span>@"Data Source=.\SQLEXPRESS;
                AttachDbFilename="</span><span>"E:\DB\NORTHWND.mdf"</span><span>";
                Integrated Security=True;Connect Timeout=30;User Instance=True"</span>);

    conn.Open();
    Console.WriteLine(<span>"打开了{0}个连接"</span>, i);
}

运行结果如下:

为什么要关闭数据库连接,可以不关闭吗?

过一会就会提示打开连接超时了:

为什么要关闭数据库连接,可以不关闭吗?

 

可以看到数据库连接时有限制的,如果连接不关闭,而且使用的人比较多,那么系统很快就down掉了。

 

但是有时候由于某些原因应用程序可能只是几个人使用,所以就有人设计了:

在应用程序启动的时候打开数据库连接,在应用程序关闭的时候关闭数据库连接

那么使用这种方式有什么问题呢?

首先假设有一张表Nums,表定义如下:

为什么要关闭数据库连接,可以不关闭吗?

Main代码如下:

SqlConnection conn = <span>new</span> SqlConnection(<span>@"Data Source=.\SQLEXPRESS;
                    AttachDbFilename="</span><span>"E:\DB\NORTHWND.mdf"</span><span>";
                    Integrated Security=True;Connect Timeout=30;User Instance=True"</span>);
conn.Open();
Parallel.For(1, 9999, (id) =>
{
    ExecuteCommand(conn, id);
});
 

就是从1到9999开始执行ExecuteCommand

 

ExecuteCommand代码如下:

<span>private</span> <span>static</span> <span>void</span> ExecuteCommand(SqlConnection conn, <span>int</span> id)
{
    Console.WriteLine(<span>"正在执行."</span> + id);

    Thread.Sleep(100);

    SqlCommand cmd = <span>new</span> SqlCommand(
       <span>string</span>.Format(<span>"Insert into Nums values('{0}') "</span>, id), conn);

    cmd.ExecuteNonQuery();
}

运行:

为什么要关闭数据库连接,可以不关闭吗?

可以看到ExecuteNonQuery方法抛出了异常,原因是连接处于关闭状态。

 

可是我们的连接一直都是open着的啊,并没有调用close,dispose之类的方法啊

于是在ExecuteCommand前面增加判断条件:

<span>if</span> (conn.State != System.Data.ConnectionState.Open)
    conn.Open();

再次运行:

为什么要关闭数据库连接,可以不关闭吗?

可以看到还是会出现连接已关闭的问题。你知道什么原因吗?

 

这里是由于多线程环境引起的。所以需要加锁。

<pre class="brush:php;toolbar:false"><span>private</span> <span>static</span> <span>object</span> syncObj = <span>new</span> <span>object</span>();
<span>private</span> <span>static</span> <span>void</span> ExecuteCommand(SqlConnection conn, <span>int</span> id)
{
    <span>lock</span> (syncObj)
    {
        <span>if</span> (conn.State != System.Data.ConnectionState.Open)
            conn.Open();
        Console.WriteLine("<span>正在执行..</span>" + id);
        Thread.Sleep(100);
        SqlCommand cmd = <span>new</span> SqlCommand(
           <span>string</span>.Format("<span>Insert into Nums values('{0}') </span>", id), conn);
        cmd.ExecuteNonQuery();
    }
}


再次运行:可以发现基本没问题了.

修改Parallel.For的最大值上限,要测试下是否可以长期执行了。

<pre class="brush:php;toolbar:false">Parallel.For(1, Int32.MaxValue, (id) =>
            {
                ExecuteCommand(conn, id);
            });

 

 

一天测试下来,没出现任何问题。

 

结论对于某些只有几个人使用的应用程序,可以不关闭数据库连接,但是在写代码的时候最好要加上连接是否打开的判断。

 

你有什么好的看法呢,欢迎留下!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

The popularity of the currency circle has returned, why do smart people have begun to quietly increase their positions? Look at the trend from the on-chain data and grasp the next round of wealth password! The popularity of the currency circle has returned, why do smart people have begun to quietly increase their positions? Look at the trend from the on-chain data and grasp the next round of wealth password! Jul 09, 2025 pm 08:30 PM

As the market conditions pick up, more and more smart investors have begun to quietly increase their positions in the currency circle. Many people are wondering what makes them take decisively when most people wait and see? This article will analyze current trends through on-chain data to help readers understand the logic of smart funds, so as to better grasp the next round of potential wealth growth opportunities.

Kane Brown's first romantic comedy movie: From the country stage to the screen! Kane Brown's first romantic comedy movie: From the country stage to the screen! Jul 04, 2025 pm 08:48 PM

Country music icon Kane Brown is about to make his film debut in the romantic comedy The Token Groomsman, joining forces with Taylor Lautner for a great show. Get ready for a screen feast with laughter and tears! From a country singer to a new face on the screen, Kane Brown opens a new chapter! Dear fans, hurry up and calm your cowboy hats! The popular country music superstar Kane Brown will leave the stage temporarily and instead enter the big screen. He will debut as the feature-length feature film in the upcoming romantic comedy "The Best Guy" - not a guest appearance, but a bold attempt to devote himself to the actor's identity! From Nashville, destination

What is a stablecoin? Why are the hot searches on Douyin discussed? What is a stablecoin? Why are the hot searches on Douyin discussed? Jul 09, 2025 am 06:03 AM

Stablecoins are cryptocurrencies that are pegged to assets such as the US dollar and aim to maintain stable value. They are mainly divided into three types: fiat currency collateral, cryptocurrency collateral and algorithms. 1. Fiat currency collateral types such as USDT and USCD are supported by US dollar reserves; 2. Cryptocurrency collateral types such as DAI need to over-collateralize other currencies; 3. Algorithm relies on smart contracts to adjust supply but have high risks. The reasons why it is hotly discussed on platforms such as Douyin include: as a hedging tool when the crypto market falls, a bridge for novices to enter the crypto world, a way to obtain high-yield financial management in DeFi, and the application of low-cost cross-border payments. To obtain stablecoins, you can trade through mainstream exchanges such as Binance, Ouyi, and Huobi.

PHP integrated AI intelligent picture recognition PHP visual content automatic labeling PHP integrated AI intelligent picture recognition PHP visual content automatic labeling Jul 25, 2025 pm 05:42 PM

The core idea of integrating AI visual understanding capabilities into PHP applications is to use the third-party AI visual service API, which is responsible for uploading images, sending requests, receiving and parsing JSON results, and storing tags into the database; 2. Automatic image tagging can significantly improve efficiency, enhance content searchability, optimize management and recommendation, and change visual content from "dead data" to "live data"; 3. Selecting AI services requires comprehensive judgments based on functional matching, accuracy, cost, ease of use, regional delay and data compliance, and it is recommended to start from general services such as Google CloudVision; 4. Common challenges include network timeout, key security, error processing, image format limitation, cost control, asynchronous processing requirements and AI recognition accuracy issues.

Is it true that Yiwu merchants start charging stablecoins? Is it true that Yiwu merchants start charging stablecoins? Jul 09, 2025 pm 07:03 PM

Yes, some merchants in Yiwu, Zhejiang have indeed begun to accept stablecoins such as USDT as a way to settle trade payments, but this phenomenon is not promoted by official policies and has not been popularized by all merchants. It is mainly a private practice adopted by individual merchants engaged in specific international trade to solve the problem of cross-border payments. 1. The reasons why merchants choose stablecoins include stable value, convenient transactions, low cost and the ability to bypass traditional payment barriers; 2. There are currently no official statistics, and it is estimated that hundreds to thousands of merchants are involved, focusing on industries with high dependence on foreign trade and customers from countries with limited payments; 3. Mainstream trading platforms include Binance, Ouyi, Huobi, Gate.io, KuCoin and Bybit. These platforms provide C2C or P2P transaction services to support fiat currency and stability

What is a DAO organization? Guide to Decentralized Autonomous Community What is a DAO organization? Guide to Decentralized Autonomous Community Jul 15, 2025 pm 07:45 PM

DAO is a decentralized autonomous organization owned and managed by community members and automatically enforces rules through smart contracts. 1. It does not have traditional management, and decisions are decided by collective voting; 2. Governance tokens give members the voting rights, the more tokens, the greater the weight; 3. Proposals are initiated and voted by the community, and will be automatically executed by the smart contract after receiving the majority support. Its core features include decentralization, autonomy and transparency, and all rules and capital flows are open and auditable. The importance of DAO is to create a more fair, efficient and cohesive collaboration model, breaking regional and identity restrictions, and improving trust and operational efficiency.

How to use PHP to combine AI to generate image. PHP automatically generates art works How to use PHP to combine AI to generate image. PHP automatically generates art works Jul 25, 2025 pm 07:21 PM

PHP does not directly perform AI image processing, but integrates through APIs, because it is good at web development rather than computing-intensive tasks. API integration can achieve professional division of labor, reduce costs, and improve efficiency; 2. Integrating key technologies include using Guzzle or cURL to send HTTP requests, JSON data encoding and decoding, API key security authentication, asynchronous queue processing time-consuming tasks, robust error handling and retry mechanism, image storage and display; 3. Common challenges include API cost out of control, uncontrollable generation results, poor user experience, security risks and difficult data management. The response strategies are setting user quotas and caches, providing propt guidance and multi-picture selection, asynchronous notifications and progress prompts, key environment variable storage and content audit, and cloud storage.

How to select a different database in Redis? How to select a different database in Redis? Jul 05, 2025 am 12:16 AM

ToswitchdatabasesinRedis,usetheSELECTcommandfollowedbythenumericindex.Redissupportsmultiplelogicaldatabases(default16),andeachclientconnectionmaintainsitsownselecteddatabase.1.UseSELECTindex(e.g.,SELECT2)toswitchtoanotherdatabase.2.Verifywithcommands

See all articles