当前位置:Gxlcms > 数据库问题 > BIN文件对象数据库,直接存储对象做数据库,小型项目用它准没错

BIN文件对象数据库,直接存储对象做数据库,小型项目用它准没错

时间:2021-07-01 10:21:17 帮助过:32人阅读

using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.IO; 6 using System.Runtime.Serialization.Formatters.Binary; 7 8 namespace MsChartHelp 9 { 10 static class FileSerialize 11 { 12 //获取文件时可以直接拿数组 13 public static T GetFileInfo<T>(string filePath) where T : new() 14 { 15 T t = new T(); 16 CreateFile<T>(filePath); 17 FileStream fs = new FileStream(filePath, FileMode.Open); 18 BinaryFormatter bf = new BinaryFormatter(); 19 if (fs.Length < 1) { return t; } 20 t = (T)(bf.Deserialize(fs)); 21 fs.Close(); 22 return t; 23 } 24 25 //BIN文件是否存在 26 private static void CreateFile<T>(string filePath) where T : new() 27 { 28 T t = new T(); 29 if (!File.Exists(filePath)) 30 { 31 FileStream fs = new FileStream(filePath, FileMode.Create); 32 BinaryFormatter bs = new BinaryFormatter(); 33 bs.Serialize(fs, t); 34 fs.Close(); 35 } 36 } 37 38 //保存数组LIST<U> 39 public static void Save<u>(string filePath, List<u> South) 40 { 41 List<u> souTrim = (List<u>)South; 42 FileStream fs = new FileStream(filePath, FileMode.Create); 43 BinaryFormatter bff = new BinaryFormatter(); 44 try 45 { 46 bff.Serialize(fs, souTrim); 47 } 48 catch (Exception) 49 { 50 51 throw; 52 } 53 finally 54 { 55 56 fs.Close(); 57 } 58 } 59 60 61 public static void Save<T>(string filePath, T South) 62 { 63 FileStream fs = new FileStream(filePath, FileMode.Create); 64 BinaryFormatter bff = new BinaryFormatter(); 65 try 66 { 67 bff.Serialize(fs, South); 68 } 69 catch (Exception) 70 { 71 72 throw; 73 } 74 finally 75 { 76 77 fs.Close(); 78 } 79 } 80 } 81 } View Code

 

 

缺点

1.如果有10w条记录,修改一条你就需要重写这个BIN文件,开销相当大,另外如果只是查询一条记录你也需要重新将这个BIN所有内容加载到内存建立对应的对象。


2.Access, SQL Server可以简单理解做了2件事情,第一他提供了统一界面,任何语言任何进程通过sql都可以与之通讯,获取数据。

第二件事情他提供了索引机制,通过索引不需要加载所有数据到内存就能根据sql定位查询结果。

3.修改对象结构会造成数据无法读取,需要保留原对象与新对象,将原数据读取至原对象,然后通过程序转换到新对象,将新对象重新保存在一个新文件(BIN)里面,最后原对象文件和原数据文件(BIN)删除。

4.实时保存,不建议实时保存,等所有处理完毕延迟保存数据最好。

但是如果你的应用很小,内存足够hold住数据,且不需要实时保存,那么此方法是可行的,而且可以说比用access都好,呵呵。

具体问题具体分析,合适就好。

BIN文件对象数据库,直接存储对象做数据库,小型项目用它准没错

标签:

人气教程排行