当前位置:网站首页>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
边栏推荐
- How to perform power regression in R
- Rapidssl getting started SSL certificate
- Eight recommended microservice testing tools
- Why should state-owned enterprises accelerate the digital transformation
- Bisection function template
- 中电投先融期货这家公司怎么样?期货开户办理安全吗?
- okcc呼叫中心数据操作的效率问题
- Sudoku (easy to understand)
- Ultimate Guide: comprehensive analysis of log analysis architecture of Enterprise Cloud native PAAS platform
- How to select the best test cases for automation?
猜你喜欢

SDL: cannot play audio after upgrading openaudio to openaudiodevice

What is decision intelligence?
congratulate! The first dragon lizard community annual outstanding contribution award is announced. Check it now
[quick news] the jeecgboot low code platform was successfully selected into the 2021 scientific innovation China · open source innovation list
![717.1-bit and 2-bit characters [sliding window]](/img/61/449566d2a8efbd403ae0361f839683.jpg)
717.1-bit and 2-bit characters [sliding window]

How can an enterprise successfully complete cloud migration?

Eight digit

Considerations for it project demand analysis

Nacos cluster starts throwing set of SQL_ SELECT_ LIMIT is not support

Three layer switching experiment
随机推荐
微服務系統設計——子服務項目構建
Skills of writing test cases efficiently
He "painted" what a smart city should look like with his oars
110. balanced binary tree
Industry Cloud video editing software
Microservice system design -- interface document management design
JS deep understanding of scope
[quick news] the jeecgboot low code platform was successfully selected into the 2021 scientific innovation China · open source innovation list
Redis learning -- list of redis operations
Leetcode skimming questions - the 72nd biweekly match and 281 weekly match
What are the grades of financial products?
"2022" plans to change jobs and raise salary. It is necessary to ask interview questions and answers - browser
Window object
okcc呼叫中心数据操作的效率问题
2022 network security C module of the secondary vocational group scans the script of the surviving target aircraft (municipal, provincial and national)
How to perform power regression in R
Rapidssl getting started SSL certificate
Usage of typedef enum (enumeration)
(Video + graphics) introduction to machine learning series - Chapter 11 support vector machines
Three years of bug free, tips for improving code quality