MultipleActiveResultSets可以使資料庫連接複用。這樣就不怕資料庫的串連資源被耗盡了。使用方法很簡單,只需要把它加到資料的連接字串中即可。
例如:server=(local);Integrated Security = true;database=AdventureWorks;MultipleActiveResultSets=true;
測試案例:
using System; using System.Threading; using System.Data.SqlClient; using System.Configuration; namespace ConsoleApplication1 { public class Example { public static void Main() { SqlConnection sql1 = new SqlConnection("server=(local);Integrated Security = true;database=AdventureWorks;"); sql1.Open(); SqlCommand comm1 = new SqlCommand(); comm1.CommandText = "select 1"; comm1.CommandType = System.Data.CommandType.Text; comm1.Connection = sql1; comm1.ExecuteNonQuery(); sql1.Close(); Console.ReadLine(); } } }
編譯後,開啟bin/debug/ConsoleApplication1.exe。
在SQL Server 2008 Management Studio中開啟一個新視窗,輸入sp_who
按F5執行,可以發現已經有一個使用者串連到AdventureWorks資料庫了。
再開啟一個ConsoleApplication1.exe,發現又會多一個使用者串連到AdventureWorks資料庫。
現在把程式的連接字串改為server=(local);Integrated Security = true;database=AdventureWorks;MultipleActiveResultSets=true;
按上面的順序執行,發現不管開啟多少個ConsoleApplication1.exe,資料庫中沒有使用者或只有一個使用者串連著AdventureWorks資料庫。
這就是資料庫連接複用的好處了。
關於資料庫連接字串的其它用法,參見: