连接池的好处就是保留连接对象,防止下次重头再来实例化一个连接对象。
(说明:可能找到结果后觉得非常简单,但怎么找到结果的,却是费了很大劲,几乎是5个小时,所以相把找到结果的过程简单说一下:
一开始用Reflector发现SqlConnection中有一个PoolGroup的属性,于是就想在运行时候比较两个SqlConnection对象的这个属性,但由于这个属性是的访问修饰符是internal的,不能直接访问,只有用反射,代码(是经过优化的)如下:
string constr1 = "Data Source=(local);Initial Catalog=AdventureWorks;Integrated Security=SSPI;";
string constr2 = "Data Source=(local);Initial Catalog=Pubs;Integrated Security=SSPI;";
string AssMark = "System.Data,Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
Assembly ass = Assembly.Load(AssMark);
Type SqlConType = null;
foreach (Type conType in ass.GetExportedTypes())
{
Console.WriteLine(conType .ToString ());
if ("System.Data.SqlClient.SqlConnection" == conType.ToString())
{
SqlConType = conType;
}
}
if (SqlConType != null)
{
Type[] types1 = new Type[0];
ConstructorInfo constructorInfoObj1 = SqlConType.GetConstructor(
BindingFlags.Instance | BindingFlags.Public, null,
CallingConventions.HasThis, types1, null);
SqlConnection con1 = (SqlConnection)constructorInfoObj1.Invoke(null);
con1.ConnectionString = constr1;
SqlConnection con2 = (SqlConnection)constructorInfoObj1.Invoke(null);
con2.ConnectionString = constr2;
PropertyInfo PI = SqlConType.GetProperty("PoolGroup", BindingFlags.Instance | BindingFlags.NonPublic);
object poolGroup1 = PI.GetValue(con1, null);
object poolGroup2 = PI.GetValue(con2, null);
}
然后在倒数第一行设置断点,为比较poolGroup1和poolGroup2的不同,结果发现,当连接字符串一样时,这两个对象的_objectID相同,字符串有一点不同就会不同,这点说明连接池中是用字符串本身比较的,而不是字符串中键值对进行比较。同还发现当con1和con2的ConnectionString不赋值时这两个对象都是null,由此说明关键是ConnectionString赋值上,所以才开始用Reflector查看这个属性的赋值方法,才有上面的代码。)