序列化与反序列化高级应用

在进行系统开发的时候序列化与反序列化在保存系统参数时可以有很大优势,比如不需要修改数据库增加字段直接修改实体就可以了,这一点对于上位机开发非常有帮助,因为上位机的电脑一般不联网,所以在上位机进行参数保存的时候建议使用序列化,但是运行参数不建议使用序列化,所谓的其实就是按照xml的方式将数据以流的方式存入数据库里面,当需要数据的时候反序列化成实体类。

1.创建可以保存流文件的表

#region 创建数据库
Dictionary<string,string> sqlDic=new Dictionary<string,string>();
string sql=string.empty;
sql+="Create table if not exists TestEntity(";
sql+="ID integer primary key autoincrement";//id设为主键
sql+=",obj blob";
sql+=");";
sqlDic.Add("Create TestEntity",sql);
#endregion

#region 插入参数表
sql="Insert into TestEntity(obj) values(";
sql+="@obj);";
sqlDic.Add("Insert TestEntity",sql);
#endregion

#region 更新参数表
sql="update TestEntity set obj=@obj ;";
sqlDic.Add("Update TestEntity",sql);
#endregion

#region 查询参数表
sql="select obj from TestEntity where ID=(select max(id) from TestEntity)";
sqlDic.Add("select TestEntity",sql);
#endregion

#region 删除参数表
sql="delete from TestEntity";
sqlDic.Add("Delete TestEntity",sql)
#endregion

2.创建类文件

[Serializable]
public class TestEntity
{
    public TestEntity()
    {
        parameter1="";
        parameter2="";
    }
    private string parameter1{set;get;}
    private string patameter2{set;get;}    
}

3.将数据序列化之后保存数据到数据库

//将一个List泛型序列化成字符串数组
public static void InsertTestEntity()
{
    List<TestEntity> listTestEntitys=new List<TestEntity> {{"Test1","Test2"},{"Test3","Test4"}};
    string sql=sqlDic["Insert TestEntity"];
    byte[] data=new byte[0];
    SerializeObjectToByte(listTestEntitys,out data);
    SaveOneBlob(sql,data);
}
//把一个实例序列化为字符串
public static bool SerializeObjectToByte(Object obj ,out byte[] serialize)
{
    bool flagSerial=false;
    try
    {
        MemoryStream memoryStream=new MemoryStream();
        BinaryFormatter binaryFormatter=new Binaryformatter();
        binaryFormatter.Serialize(memoryStream,obj);
        serialize=memoryStream.ToArray();
        flagSerial=true;
    }
    catch(Exception ex)
    {
        flagSerial=false;
        throw ex;
    }
    return flagSerial;
}

//comm是一个Command对象
//conn是一个Connectiond对象
//tran是一个Transaction对象
//保存blob对象
public static void SaveBlob(string sqlstr,byte[] buffer)
{
    try
    {
        openConnection();
        tran=conn.BeginTransaction(IsolationLevel.ReadCommitted);
        comm.Transaction=tran;
        comm.CommandType=CommandType.Text;
        comm.CommandTest=sqlstr;
        comm.Parameters.Add("@obj",System.Data.DbType.Binary,buffer.Length).Value=buffer;
        comm.ExecuteNonQuery();
        trans.Commit();
    }
    catch(Exception e)
    {
        throw new Exception(e.Message);
    }
    finally
    {
        closeConnection();
    }
}

4.从数据库读取流之后反序列化为实体泛型

public static void GetTextEntity()
{
    try
    {
        List<TextEntity> ListTestEntitys=new List<TextEntity>();
        string sql=sqlDic["Select TestEntity"];
        byte[] data=GetOleObj(sql);
        if(data!=null&&data.Length>0)
        {
            object obj=new object();
            DeserializeToObj(data,out obj);
            if(obj!=null)
            {
                ListTestEntitys=(List<TextEntity>)obj;
            }
        }
    }
    catch(Exception ex)
    {
        throw ex;
    }
}
//查询数据库,获取数据流,以字节数组的形式返回
public static byte[] GetOleObj(string sql)
{
    byte[] r=new byte[0];
    try
    {
        openConnection();
        comm.CommandType=CommandType.Text;
        comm.CommandText=sql;
        r=(byte[])comm.ExecuteScalar;
        if(r==null)
        {
            r=new byte[0];
        }
    }
    catch(Exception e)
    {
        throw ex;
    }
    finally
    {
     closeConnection();
    }
    return r;
}
//将字符流反序列化为实体类
public static bool DeserializeToObj(byte[] serialize,out object deserializedObj)
{
    bool deserializeOK=false;
    deserializedObj=null;
    try
    {
        MemoryStream restoreMemoryStream=new MemoryStream(serialize);
        BinaryFormatter binaryFormatter=new BinaryFormatter();
        deserializedObj=binaryFormatter.Deserialize(restoreMemoryStream);
        deserializeOK=true;
    }
    catch(Exception ex)
    {
        throw ex;
    }
    return  deserializedObj;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值