ADO.NET 拾遗

一、SqlDataReader和SqlDataAdapter性能对比

 1  Stopwatch sw = new Stopwatch();  2  sw.Start();  3             using(SqlConnection cnn = new SqlConnection(@"Data Source=RuyeeSoft\SqlExpress;user id=sa;password=123;Initial catalog=NorthWind"))  4  {  5                 SqlCommand cmd = cnn.CreateCommand();  6                 cmd.CommandText = "select top(2000000) * from student";  7  cnn.Open();  8                 SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);  9 
10                 DataTable auto = new DataTable("Auto"); 11 
12                 DataColumn vin = new DataColumn("ID"); 13                 vin.DataType = typeof(int); 14                 vin.Unique = true; 15                 vin.AllowDBNull = false; 16                 vin.Caption = "ID"; 17  auto.Columns.Add(vin); 18 
19 
20                 DataColumn Name = new DataColumn("Name"); 21                 Name.DataType = typeof(string); 22                 Name.MaxLength = 23; 23                 //Name.Unique = true;
24                 Name.AllowDBNull = false; 25                 Name.Caption = "Name"; 26  auto.Columns.Add(Name); 27 
28                 DataColumn score = new DataColumn("score"); 29                 score.DataType = typeof(int); 30                 //score.Unique = true;
31                 score.AllowDBNull = false; 32                 score.Caption = "score"; 33  auto.Columns.Add(score); 34 
35                 while (rdr.Read()) 36  { 37                     DataRow newAuto = auto.NewRow(); 38                     newAuto["ID"] = rdr.GetInt32(0); 39                     newAuto["score"] = rdr.GetInt32(2); 40                     newAuto["Name"] = rdr.GetString(1); 41  auto.Rows.Add(newAuto); 42  } 43  } 44  sw.Stop(); 45             Console.WriteLine("1总运行时间:" + sw.Elapsed); 46             
47  sw.Start(); 48             using (SqlConnection cnn = new SqlConnection(@"Data Source=ruyeesoft\SqlExpress;user id=sa;password=123;Initial catalog=NorthWind")) 49  { 50                 SqlCommand cmd = cnn.CreateCommand(); 51                 cmd.CommandText = "select top(2000000) * from student"; 52                 SqlDataAdapter sda = new SqlDataAdapter(cmd); 53                 DataTable dt = new DataTable(); 54  cnn.Open(); 55  sda.Fill(dt); 56  } 57  sw.Stop(); 58             Console.WriteLine("2总运行时间:" + sw.Elapsed);

对比结果

100万条数据的效果
1总运行时间:00:00:11.3748084
2总运行时间:00:00:18.0405345

200万条数据的效果
1总运行时间:00:00:24.1619173
2总运行时间:00:00:37.6120735

二、使用非连接数据

1、关于并发:

由于不同的客户端拿到了相同版本的副本,修改后都要讲结果保存到数据库中,这时出现了以哪个修改后的副本为最新版本的决策冲突问题。

2、解决并发冲突:

a、时间优先:第一次更新优先。

b、时间优先:最后一次更新优先。

c、角色优先:看获取副本的客户端的权限级别,谁级别高以谁为准。

d、位置优先:如总部优先与分店。

e、用户解决冲突:提供一个解决冲突界面,让用户选择数据的版本。如tfs的版本冲突解决策略。

3、应该加载什么离线数据

a、数据选择:应该只加载用户需要处理的数据,而不是加载整个数据库。

b、数据量:数量量的大小会影响加载的时间、更新的时间和客户的内存需求量。

c、分割数据:根据业务的使用目的,最好将数据分割成多个部分,并分别存入相应的DataSet对象中。不能在不同的DataSet对象的DataTable对象之间建立外键约束。

4、为了更好的使用离线数据,请使用GUID作为数据库的主键。

你可能感兴趣的:(.net)