【问题标题】:Serialize an object into SQL Server using C#使用 C# 将对象序列化为 SQL Server
【发布时间】:2013-07-04 13:48:49
【问题描述】:

我有以下写入 SQL Server 数据库的代码:

private void InsertResult(Result results, string messageId)
{
   object chkresult = (results);

   MemoryStream memStream = new MemoryStream();
   StreamWriter sw = new StreamWriter(memStream);

   sw.Write(chkresult);

   SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["Reporting"].ConnectionString);

   using (conn)
   {
      using (SqlCommand cmd = new SqlCommand())
      {
         conn.Open();

         cmd.CommandText = "Results_Ins";
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.Add("@Id", SqlDbType.VarChar, 50).Value = messageId;
         cmd.Parameters.Add("@result", SqlDbType.VarBinary, Int32.MaxValue);
         cmd.Parameters["@result"].Value = memStream.GetBuffer();
         cmd.Parameters.Add("@RowCount", SqlDbType.Int).Direction = ParameterDirection.Output;

         cmd.Connection = conn;

         try
         {
             cmd.ExecuteNonQuery();
         }
         catch (Exception err)
         {
             // handle the error
             //messageInsert = false;
         }
         finally
         { 
             conn.Close(); 
         }
      }
   }

   //return rowCount;
}

当我执行此代码时,我得到 0x 存储在 Result 列中。我不确定这是否正确,因此我需要一些帮助。

基本上,我需要将一个完整的对象存储到 SQL Server 数据库表的单个列中。

【问题讨论】:

    标签: c# max varbinary


    【解决方案1】:

    您需要调用Flush 或将sw 设置为Closed 或Disposed,以确保完成对memStream 的写入。

    此外,您应该使用ToArray,而不是GetBufferGetBuffer 返回一个内部缓冲区,它可能大于实际写入的字节数。


    你也应该改变这个:

    catch (Exception err)
    {
       // handle the error
       //messageInsert = false;
    }
    

    只捕获您有策略处理的特定异常。


    而且,即使是现在,我也不认为它会如你想要(你还没有真正说明)。你的sw.Write 调用所做的所有is

    通过调用对象的 ToString 方法将对象的文本表示写入文本字符串或流。

    如果您希望发生实际的序列化,您将需要编写导致它发生的代码 - 在选择您想要执行binary 还是xml 序列化之后。

    【讨论】:

    • 嗨,Damien,因此进行建议性更改现在已将 ServiceReference1.Result 存储在 th 字段中。因此,该对象(来自 Web 服务)现在似乎已保存。您有任何关于如何将其转换回来的示例吗?
    • @CSharpNewBee - 请注意我最近在底部添加的内容 - 您当前存储的所有内容都是在 results 上调用 ToString() 的结果 - 默认情况下只是类型名称。您需要确定您实际想要执行的序列化类型(我已链接到两个标准的 .NET 序列化),然后编写代码来执行此操作。
    • 我明白了,我们的消息是相互传递的 :-) 所以,我只是将名称存储到对象中。也许,我需要做更多的阅读,因为我认为这个方法会写入对象。
    猜你喜欢
    • 2015-12-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-17
    • 2015-08-05
    相关资源
    最近更新 更多