使用using释放资源
理解using的作用
使用Connection,如何保证连接关闭
以前我们使用的是try…catch…final的方式,将数据库连接语句放在里面,在final语句块中写关闭语句。
使用using释放Connection对象
- using的用法一:导入命名空间
- 释放对象占用的资源,比如:Connection、DataReader、FileStream 等等
写法:
using(类型 对象名 = new 类型(参数列表))
{
//…
//…
}
大括号是声明using的有效范围,括号内是对象的适用范围,一旦出了这个使用范围,程序会自动释放程序内部对象。
using(SqlConnection conn = new SqlConnection(connString))
{
conn.open();
//......
}
不需要显式调用Close()方法。
例子如下:
#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);//观看执行状态是否关闭
Console.WriteLine(count);
Console.ReadLine();
}
}
}
使用using释放SqlDataReader
using(sqlDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
{
while(reader.Read())
{
//遍历查询结果
}
}
CommandBehavior.CloseConnection 是保证DataReader释放后自动释放Connection。
例子如下:
#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))//顺便关闭SqlConnection对象
{
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);//观看执行状态是否关闭
// Console.WriteLine(count);
Console.ReadLine();
}
}
}
using的本质
相当于在try-catch-finally的finally块中调用了对象名.Dispose()方法。
- Dispose()是IDisable接口的方法
- Dispose()专用于释放对象稀缺资源
- object类实现了Dispose(),部分类实现了Close()
- Close()封装了对Dispose()的调用