0

I have the following method i am using to save an object into an SQL Server CE database. 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;
    }
2
  • When you say "put the record back out", do you mean removing the record from the database (i.e. deleting it), or just getting the record's data to display or something?
    – jaredk
    Feb 6, 2014 at 15:45
  • I update the post and add some more specifics
    – Greg Hunt
    Feb 6, 2014 at 15:53

1 Answer 1

0

I think the problem most likely lies in the fact that the size of the @Image parameter is being set to 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));

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.