- using System;
- using System.Configuration;
- using System.Data.SqlClient;
- using System.Diagnostics;
- namespace ConsoleApplication1
- {
- class connect
- {
- static void Main(string[] args)
- {
- string _connString = "Data Source=SAMEWAYDEV06;Initial Catalog=DataImport;Persist Security Info=True;User ID=sa;Password=sa";
- SqlConnection conn = new SqlConnection(_connString);
- Stopwatch sw = new Stopwatch();
- sw.Start();
- conn.Open();
- sw.Stop();
- Console.WriteLine("1连接所用时间:{0}", sw.ElapsedTicks.ToString());
- conn.Close();//关闭连接
- sw.Reset();
- sw.Start();
- conn.Open();//现在是直接从连接池中分配的连接,所以速度要快很多
- sw.Stop();
- Console.WriteLine("2连接所用时间:{0}", sw.ElapsedTicks.ToString());
- conn.Dispose();//释放连接
- conn.ConnectionString = _connString;
- sw.Reset();
- sw.Start();
- conn.Open();//Dispose()后,仍然可以连接!(前提是必须重设连接字符串)
- sw.Stop();
- Console.WriteLine("3连接所用时间:{0}", sw.ElapsedTicks.ToString());//从输出结果上看,这一次仍然要比首次连接快很多,貌似也是从连接池中取的
- conn.Close();
- using (SqlConnection conn2 = new SqlConnection(_connString))
- {
- try
- {
- sw.Reset();
- sw.Start();
- conn2.Open();//即使创建一个完全不同的新Connection对象,只要连接字符串相同,仍然会从连接池内中分配已有连接,所以速度仍然很快
- sw.Stop();
- Console.WriteLine("4连接所用时间:{0}", sw.ElapsedTicks.ToString());
- }
- catch (Exception)
- {
- throw;
- }
- finally
- {
- conn2.Close();
- }
- }
- //连续多次调用Close()或Dispose()不会抛出异常,但连续多次调用Open()会抛出异常
- //conn.Close();
- //conn.Close();
- //conn.Dispose();
- //conn.Dispose();
- Console.Read();
- //即使不关闭连接,程序退出时,连接也被会自动销毁
- }
- }
- }
1连接所用时间:480219
2连接所用时间:130
3连接所用时间:60
4连接所用时间:47
- using System;
- using System.Reflection;
- namespace console
- {
- class Program
- {
- static void Main(string[] args)
- {
- //不会改变
- int i = 4;
- Console.WriteLine("before change,i = {0}", i);
- changeint(i, 5);
- Console.WriteLine("after change,i = {0}", i);
- //改变
- Ints ii =new Ints(){i =4};
- Console.WriteLine("before change,ii = {0}", ii.i);
- changeints(ii, 5);
- Console.WriteLine("after change,ii = {0}", ii.i);
- //改变
- Ints ii2 = new Ints() { i = 4 };
- Console.WriteLine("before change,ii = {0}", ii2.i);
- changeints2(ref ii2, 5);
- Console.WriteLine("after change,ii = {0}", ii2.i);
- //反射修改private属性
- peason p = new peason();
- PropertyInfo info = p.GetType().GetProperty("Name");
- info.SetValue(p, "xueyong", null);
- Console.WriteLine(p.Name);
- }
- static void changeint(int i, int j)
- {
- i = j;
- }
- static void changeints(Ints m, int p)
- {
- m.i = p;
- }
- static void changeints2(ref Ints m, int p)
- {
- m.i = p;
- }
- }
- public class Ints
- {
- public int i { set; get; }
- }
- public class peason
- {
- private string _name;
- public string Name
- {
- private set
- {
- _name = value;
- }
- get
- {
- return _name;
- }
- }
- }
- }