using 语句允许程序员指定使用资源的对象应当何时释放资源。为 using 语句提供的对象必须实现 IDisposable接口。此接口提供了 Dispose 方法,该方法将释放此对象的资源。
可以在到达 using 语句的末尾时,或者在该语句结束之前引发了异常并且控制权离开语句块时,退出 using 语句。
可以在 using 语句中声明对象(如上所示),或者在 using 语句之前声明对象,如下所示:
Font font2 = new Font("Arial", 10.0f); using (font2) { // use font2 }
可以有多个对象与 using 语句一起使用,但是必须在 using 语句内部声明这些对象,如下所示:
using (Font font3 = new Font("Arial", 10.0f), font4 = new Font("Arial", 10.0f)) { // Use font3 and font4. }
我是这样理解的在Page_Load下连接SQL Server 2005
string connectionString = "server=localhost;database=Northwind;integrated security=SSPI";
SqlConnection mySqlConnection = new SqlConnection(connectionString);
using (mySqlConnection)
{
mySqlConnection.Open();
lblInfo.Text = "<b>mySqlConnection对象的ConnectionString属性为:<b>" +
mySqlConnection.ConnectionString + "<br>";
lblInfo.Text += "<b>mySqlConnection对象的ConnectionTimeout属性为<b>" +
mySqlConnection.ConnectionTimeout + "<br>";
lblInfo.Text += "<b>mySqlConnection对象的Database属性为<b>" +
mySqlConnection.Database + "<br>";
lblInfo.Text += "<b>mySqlConnection对象的DataSource属性为<b>" +
mySqlConnection.DataSource + "<br>";
lblInfo.Text += "<b>mySqlConnection对象的ServerVersion属性为<b>" +
mySqlConnection.ServerVersion + "<br>";
lblInfo.Text += "<b>mySqlConnection对象的当前状态为<b>"+
mySqlConnection.State + "<br>";
}
lblInfo.Text += "<br><b>关闭连接后的mySqlConnection对象的状态为:</b>";
lblInfo.Text += mySqlConnection.State.ToString();
这样就不用写
try{}
catch(Exception e){}
finally{}
显示的关闭数据连接 在超过using的范围会自动关闭