ASP.NET2.0 SQL Server数据库连接详解
当然,我们还可以采用一种更加简便的方法来实现上述程序的功能。这就是将SqlConnection对象包含到using区块中,这样程序会自动调用 Dispose()方法释放SqlConnection对象所占用的系统资源,无需再使用SqlConnection对象的Close()方法。 02 { 03 protected void Page_Load(object sender, EventArgs e) 04 { 05 string connectionString = "server=localhost;database=Northwind; 06 integrated security=SSPI"; 07 SqlConnection mySqlConnection = new SqlConnection(connectionString); 08 using (mySqlConnection) 09 { 10 mySqlConnection.Open(); 11 lblInfo.Text = "<b>mySqlConnection对象的ConnectionString属性为:<b>" + 12 mySqlConnection.ConnectionString + "<br>"; 13 lblInfo.Text += "<b>mySqlConnection对象的ConnectionTimeout属性为<b>" + 14 mySqlConnection.ConnectionTimeout + "<br>"; 15 lblInfo.Text += "<b>mySqlConnection对象的Database属性为<b>" + 16 mySqlConnection.Database + "<br>"; 17 lblInfo.Text += "<b>mySqlConnection对象的DataSource属性为<b>" + 18 mySqlConnection.DataSource + "<br>"; 19 lblInfo.Text += "<b>mySqlConnection对象的PacketSize属性为<b>" + 20 mySqlConnection.PacketSize + "<br>"; 21 lblInfo.Text += "<b>mySqlConnection对象的ServerVersion属性为<b>" + 22 mySqlConnection.ServerVersion + "<br>"; 23 lblInfo.Text += "<b>mySqlConnection对象的当前状态为<b>"+ 24 mySqlConnection.State + "<br>"; 25 } 26 lblInfo.Text += "<br><b>关闭连接后的mySqlConnection对象的状态为:</b>"; 27 lblInfo.Text += mySqlConnection.State.ToString(); 28 } 29 }
连接池 integrated security=SSPI;"+"max pool size=10;min pool size=5");
02 { 03 protected void Page_Load(object sender, EventArgs e) 04 { 05 //设置连接池的最大连接数为5,最小为1 06 SqlConnection mySqlConnection =new SqlConnection( 07 "server=localhost;database=Northwind;integrated security=SSPI;"+ 08 "max pool size=5;min pool size=1"); 09 //新建一个StringBuilder对象 10 StringBuilder htmStr = new StringBuilder(""); 11 for (int count = 1; count <= 5; count++) 12 { 13 //使用Append()方法追加字符串到StringBuilder对象的结尾处 14 htmStr.Append("连接对象 "+count); 15 htmStr.Append("<br>"); 16 //设置一个连接的开始时间 17 DateTime start = DateTime.Now; 18 mySqlConnection.Open(); 19 //连接所用的时间 20 TimeSpan timeTaken = DateTime.Now - start; 21 htmStr.Append("连接时间为 "+timeTaken.Milliseconds+"毫秒"); 22 htmStr.Append("<br>"); 23 htmStr.Append("mySqlConnection对象的状态为" + mySqlConnection.State); 24 htmStr.Append("<br>"); 25 mySqlConnection.Close(); 26 } 27 //将StringBuilder对象的包含的字符串在label控件中显示出来 28 lblInfo.Text = htmStr.ToString(); 29 } 30 }
(编辑:焦作站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |