当前位置:网站首页>Using to release resources
Using to release resources
2022-06-24 18:39:00 【MousseIn】
Use using Release resources
understand using The role of
Use Connection, How to ensure that the connection is closed
We used to use try…catch…final The way , Put the database connection statement inside , stay final Write a close statement in a statement block .
Use using Release Connection object
- using One of the usages of : Import namespace
- Release the resources occupied by the object , such as :Connection、DataReader、FileStream wait
How to write it :
using( type Object name = new type ( parameter list ))
{
//…
//…
}
Braces are declarations using The effective range of , In parentheses is the scope of application of the object , Once out of this scope of use , The program will automatically release its internal objects .
using(SqlConnection conn = new SqlConnection(connString))
{
conn.open();
//......
}
There is no need to explicitly call Close() Method .
Examples are as follows :
#region bage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
#endregion
namespace CH03
{
class Program
{
static void Main(string[] args)
{
string sql = "select count(*) from dbo.Grade";
string conStr = "server=.;database=MySchool;uid=sa;pwd=123456";
int count = 0;
SqlConnection con = null;
using( con = new SqlConnection(conStr))
{
con.Open();
SqlCommand cmd = new SqlCommand(sql,con);
count = Convert.ToInt32(cmd.ExecuteScalar());
//con.Close();
}
Console.WriteLine(con.State);// Check whether the execution status is closed
Console.WriteLine(count);
Console.ReadLine();
}
}
}
Use using Release SqlDataReader
using(sqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while(reader.Read())
{
// Traverse query results
}
}
CommandBehavior.CloseConnection It's a guarantee DataReader Automatically release after release Connection.
Examples are as follows :
#region bage
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
#endregion
namespace CH03
{
class Program
{
static void Main(string[] args)
{
//string sql = "select count(*) from dbo.Grade";
string sql = "select * from dbo.Grade";
string conStr = "server=.;database=MySchool;uid=sa;pwd=123456";
// int count = 0;
SqlConnection con = new SqlConnection(conStr);
con.Open();
SqlCommand cmd = new SqlCommand(sql,con);
using(SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection))// Close by the way SqlConnection object
{
while (reader.Read())
{
Console.WriteLine(reader[0]+" "+reader[1]);
}
}
//using( con = new SqlConnection(conStr))
//{
// con.Open();
// SqlCommand cmd = new SqlCommand(sql,con);
// count = Convert.ToInt32(cmd.ExecuteScalar());
// //con.Close();
//}
Console.WriteLine(con.State);// Check whether the execution status is closed
// Console.WriteLine(count);
Console.ReadLine();
}
}
}
using The essence of
Equivalent to the try-catch-finally Of finally The object name is called in the block .Dispose() Method .
- Dispose() yes IDisable Interface method
- Dispose() Dedicated to releasing scarce resources of objects
- object Class implements the Dispose(), Some classes implement Close()
- Close() Encapsulates the Dispose() Call to
Master the use of using Release resource objects
边栏推荐
- [quick news] the jeecgboot low code platform was successfully selected into the 2021 scientific innovation China · open source innovation list
- Specification for self test requirements of program developers
- 微服务系统设计——子服务项目构建
- JS event details
- Three years of bug free, tips for improving code quality
- Recommend a distributed JVM monitoring tool, which is very practical!
- Cloud service selection of enterprises: comparative analysis of SaaS, PAAS and IAAs
- Bigdecimalavoiddoubleconstructorrule: do not directly use the double variable as a parameter to construct BigDecimal
- Monotone stack template
- Crmeb multi merchant PC packaging tutorial
猜你喜欢

SAP license: ERP for supply chain management and Implementation

Flutter dart regular regexp special characters $, () (IV)

He "painted" what a smart city should look like with his oars

SDL: cannot play audio after upgrading openaudio to openaudiodevice

Overall planning and construction method of digital transformation
[golang] leetcode intermediate - jumping game & different paths

ASP. Net hosting uploading file message 500 error in IIS

2022 network security C module of the secondary vocational group scans the script of the surviving target aircraft (municipal, provincial and national)

Wechat applet development - Implementation of rotation chart

Eight digit
随机推荐
Two micro service interviews where small companies suffer losses
Exception: Gradle task assembleDebug failed with exit code 1
Data modeling technology of Business Intelligence BI
解决执行MapReduce程序控制台没有日志信息WARN Please initialize the log4j system properly
The country has made a move! Launch network security review on HowNet
JS string method
Monotone stack template
696. count binary substring
如何在 R 中执行稳健回归
Analysis on the issue of raising the right of MSSQL in 2021 secondary vocational group network security competition in Shandong Province
130. surrounding area
Sword finger offer 10- ii Frog jumping on steps
Ten excellent business process automation tools for small businesses
Easygbs video platform TCP active mode streaming exception repair
JS clothing photo album case
DOM (document object model)
Location object
Solve the problem that the MapReduce program console does not have log information warn please initialize the log4j system properly
Regression testing strategy for comprehensive quality assurance system
JS deep understanding of scope