简体   繁体   English

从SQL Server CE数据库检索SqlDbType.Image类型的数据

[英]Retrieving data of type SqlDbType.Image from SQL Server CE database

I have the following method i am using to save an object into an SQL Server CE database. 我使用以下方法将对象保存到SQL Server CE数据库中。 I am now stuck on how to get the record back out. 我现在停留在如何找回记录上。

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();
        }
    }

Update 更新资料

I am looking to make another class that returns a specific record. 我正在寻找另一个返回特定记录的类。

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

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

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

        return returnRecord;
    }

I think the problem most likely lies in the fact that the size of the @Image parameter is being set to Int32.MaxValue 我认为问题很可能是因为@Image参数的大小设置为Int32.MaxValue

Set it instead to the length of the image byte stream: 改为将其设置为图像字节流的长度:

byte[] imgBytes = memStream.GetBuffer();

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

Here's an excerpt from this example (modified for your question) of how you might go about retrieving the image: 这是此示例 (针对您的问题进行了修改)的摘录,内容涉及如何获取图像:

// 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));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM