当前位置:网站首页>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
边栏推荐
- What are the reasons for the abnormal playback of the online channel of the channel accessed by easycvr national standard protocol?
- How does the video platform import the old database into the new database?
- (Video + graphics) introduction to machine learning series - Chapter 11 support vector machines
- Five advantages and disadvantages of Bi
- Common MySQL commands of installation free version
- Uniapp wechat applet calls mobile map to navigate to the target point
- Gateway solves cross domain access
- congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now
- Different JVM
- Tencent cloud TCS: an application-oriented one-stop PAAS platform
猜你喜欢

Redis learning -- list of redis operations

JS deep understanding of functions

微服務系統設計——子服務項目構建

Project Management Guide: tips, strategies and specific practices

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

History object

Overall planning and construction method of digital transformation

How to use Fisher's least significant difference (LSD) in R

JS pre parsing

【leetcode】838. Push domino (Analog)
随机推荐
Creating a new MySQL user in Amazon RDS environment - creating a new MySQL user in Amazon RDS environment
Common MySQL commands of installation free version
How do yaml files and zmail collide with the spark of the framework, and how can code and data be separated gracefully?
How to perform robust regression in R
What are the grades of financial products?
Uniapp wechat applet calls mobile map to navigate to the target point
Get max value of a bit column - get max value of a bit column
Project Management Guide: tips, strategies and specific practices
Microservice system design -- data model and system architecture design
Industry Cloud video editing software
Top ten popular codeless testing tools
He "painted" what a smart city should look like with his oars
[NLP] 3 papers on how Stanford team builds a better chat AI
Selection (033) - what is the output of the following code?
Flex box flex attribute
微服务系统设计——数据模型与系统架构设计
Knowledge points of 2022 system integration project management engineer examination: ITSS information technology service
Data modeling technology of Business Intelligence BI
JS pre parsing
JS local storage