2014-02-06 118 views
0

我使用以下方法将对象保存到SQL Server CE数据库中。我现在停留在如何取回记录。从SQL Server CE数据库中检索SqlDbType.Image类型的数据

public void SaveRecord(LabRecord _labrecord) 
{ 
     try 
     { 
      conn = new SqlCeConnection(_connectionString); 
      conn.Open(); 
      MemoryStream memStream = new MemoryStream(); 
      StreamWriter sw = new StreamWriter(memStream); 

      sw.Write(_labrecord); 

      SqlCeCommand sqlCmd = new SqlCeCommand("INSERT INTO LabTransactions([TrasactionType], [CAM], [TransactionObject]) VALUES ('ResultTest', 1234, @Image)", conn); 

      sqlCmd.Parameters.Add("@Image", SqlDbType.Image, Int32.MaxValue); 

      sqlCmd.Parameters["@Image"].Value = memStream.GetBuffer(); 

      sqlCmd.ExecuteNonQuery(); 

     } 
     finally 
     { 
      conn.Close(); 
     } 
    } 

更新

我期待再拍类返回一个特定的记录。

public LabRecord getRecord(int transactionId) 
{ 
     LabRecord returnRecord = null; 

     try 
     { 
      conn = new SqlCeConnection(_connectionString); 
      conn.Open(); 

      //.... Get the record 
     } 
     finally 
     { 
      conn.Close(); 
     } 

     return returnRecord; 
    } 
+0

当你说“把记录放回去”时,你的意思是从数据库中删除记录(即删除它),还是只是获取记录的数据来显示? – jaredk

+0

我更新帖子并添加一些更多细节 –

回答

0

我认为问题最有可能出在事实@Image参数的大小被设置为Int32.MaxValue

设置它,而不是在图像字节流的长度:

byte[] imgBytes = memStream.GetBuffer(); 

sqlCmd.Parameters.Add("@Image", SqlDbType.Image, imgBytes.Length); 
sqlCmd.Parameters["@Image"].Value = imgBytes; 

这里是摘录from this example(针对您的问题进行了修改)您可能会如何去检索图像:

// Get the record 
SqlCeCommand cmd = new SqlCeCommand("Select [TransactionObject] From LabTransactions Where [CAM] = 1234", conn); 
conn.Open(); 
SqlCeDataReader sdr = cmd.ExecuteReader(); 
byte[] imgByteData = Convert.ToByte(sdr.Item("Picture")); 
Bitmap bitmap = new Bitmap(new System.IO.MemoryStream(imgByteData));