Ok, lots of people have asked the question and I want to clear this up good and proper. Here is how under Compact Framework 2, you can both insert images into a SQL Compact database and pull them out again. This is particularly useful for putting camera images or signatures reliably (I feel the need to say reliably again), into and out the database.
Lots has been written about this, but comrades this really does work -
Today we'll do getting images out of the database and into a nice Bitmap variable.
To get an image from the database the only way I've found that works reliably
is using the ExecuteScalar like -
public Bitmap GetOurImage()
{
StringBuilder sbsql = new StringBuilder();
sbsql.Append("SELECT ");
sbsql.Append("[Picture] "); // This is an image field in the database
sbsql.Append("FROM ");
sbsql.Append("[SOME TABLE]");
object y = SqlQuickValue(sbsql.ToString()); // little helper function as I'm lazy
MemoryStream msimageblob = new MemoryStream((byte[])y);
Bitmap picture = new Bitmap(msimageblob);
msimageblob.Close();
return picture;
}
protected object SqlQuickValue(string strsql)
{
SqlCeCommand cmd = null;
object ret = null;
try
{
cn.Open();
cmd = new SqlCeCommand(strsql, cn); // note cn - is a sqlceconnection object
cmd.CommandType = CommandType.Text;
}
catch
{
if (cmd != null) cmd.Dispose();
cn.Close();
return ret;
}
try
{
ret = cmd.ExecuteScalar();
}
catch (SqlCeException e)
{
}
finally
{
cmd.Dispose();
}
cn.Close();
return ret;
}
Tomorrow, I'll show you how we can insert records into the database.