群里有朋友问起连接池在密码修改后的变化,特地做了下测试
使用连接池,连接字符串为:
string connString = "Data Source=.;Initial Catalog=DemoDB1;Integrated Security=False;User ID=DBA;Password=XXXXX;Pooling=True;Connect Timeout=60";
测试1
数据库连接打开后不断开(不调用close方法),连续请求
using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); for (int i = 0; i < 100; i++) { SqlCommand comm = conn.CreateCommand(); comm.CommandText = "SELECT COUNT(1) FROM TB2"; comm.CommandType = System.Data.CommandType.Text; Console.WriteLine(comm.ExecuteScalar().ToString()); Console.WriteLine(DateTime.Now.ToString()); System.Threading.Thread.Sleep(1 * 1000); } }
测试结果:修改密码后,程序没有任何报错,对已建立的连接没有影响
测试2
循环执行请求,每次请求会关闭链接(using会调用close方法)
for (int i = 0; i < 100; i++) { using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); SqlCommand comm = conn.CreateCommand(); comm.CommandText = "SELECT COUNT(1) FROM TB2"; comm.CommandType = System.Data.CommandType.Text; Console.WriteLine(comm.ExecuteScalar().ToString()); Console.WriteLine(DateTime.Now.ToString()); System.Threading.Thread.Sleep(1 * 1000); } }
测试结果:程序运行后,可以使用SQL Profiler捕获到exec sp_reset_connection,当密码修改后,程序立即报错(在命令执行时报错)。
测试3
注释掉执行命令语句,查看conn.Open()是否执行sp_reset_connection
for (int i = 0; i < 100; i++) { using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); SqlCommand comm = conn.CreateCommand(); comm.CommandText = "SELECT COUNT(1) FROM TB2"; comm.CommandType = System.Data.CommandType.Text; //Console.WriteLine(comm.ExecuteScalar().ToString()); Console.WriteLine(DateTime.Now.ToString()); System.Threading.Thread.Sleep(1 * 1000); } }
测试结果:无法使用SQL Profiler 捕获到sp_reset_connection
测试4
在重用的连接中执行两次命令,查看是否调用两次sp_reset_connection
for (int i = 0; i < 100; i++) { using (SqlConnection conn = new SqlConnection(connString)) { conn.Open(); SqlCommand comm = conn.CreateCommand(); comm.CommandText = "SELECT COUNT(1) AS COUNT1 FROM TB2"; comm.CommandType = System.Data.CommandType.Text; Console.WriteLine(comm.ExecuteScalar().ToString()); Console.WriteLine(DateTime.Now.ToString()); System.Threading.Thread.Sleep(10 * 1000); comm.CommandText = "SELECT COUNT(1) AS COUNT2 FROM TB2"; Console.WriteLine(comm.ExecuteScalar().ToString()); System.Threading.Thread.Sleep(10 * 1000); } }
测试结果:对于重用的连接,无论执行多少次命令,都只调用一次sp_reset_connection
结论:
1.对于第一次打开后的连接,不会调用 sp_reset_connection,修改密码仍然能执行请求,没有照成影响;
2.对于重用的连接,执行OPEN不会调用sp_reset_connection
3.对于重用的连接,第一次执行命令时sp_reset_connection,后续执行命令不调用sp_reset_connection
4.对于重用的连接,在sp_reset_connection时会验证,密码修改后,执行sp_reset_connection会验证失败,抛出异常
参考链接:http://msdn.microsoft.com/zh-cn/library/8xx3tyca(v=vs.110).aspx
妹子镇贴: