将图像保存到Access数据库中

时间:2013-11-27 08:10:50

标签: c# ms-access-2007

我正在尝试使用c#应用程序保存数字,日期时间和图像以访问数据库。 我编写了一个函数,将图像转换为base64string格式,然后我使用该函数将图像作为字符串,然后保存。 但是我得到一个错误,说'参数NULL异常未处理'。此错误发生在代码中的以下行 image.Save(stream,image.RawFormat); *

我的代码如下:

private void save_Click(object sender, System.EventArgs e)
{
    string oneimg=ImageToBase64String(pictureBox1.Image);
    string twoimg=ImageToBase64String(pictureBox2.Image);
    OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Windows\roadsafety.accdb;Jet OLEDB:Database Password=sudeep;");
    con.Open();
    try
    {
    //    con.Open();

    OleDbCommand cmd = new OleDbCommand("insert into dashboard(id,dtime) values('" + textBox2.Text + "','" + DateTime.Now.ToString() + "','" + oneimg + "','" + twoimg + "')", con);
    cmd.ExecuteReader();
    MessageBox.Show("Succesfully saved");
    }

    catch (Exception k)
    {
        MessageBox.Show(k.ToString());
    }
}

private string ImageToBase64String(Image image)
{
    using (MemoryStream stream = new MemoryStream())
    {
        image.Save(stream, image.RawFormat);
        return Convert.ToBase64String(stream.ToArray());
    }
}

请帮忙

1 个答案:

答案 0 :(得分:0)

OleDbConnection myConnection = null;
try
{
   //save image to byte array and allocate enough memory for the image
   byte[] imagedata = image.ToByteArray(new Atalasoft.Imaging.Codec.JpegEncoder(75));

   //create the SQL statement to add the image data
   myConnection = new OleDbConnection(CONNECTION_STRING);
   OleDbCommand myCommand = new OleDbCommand("INSERT INTO Atalasoft_Image_Database (Caption, ImageData) VALUES ('" + txtCaption.Text + "', ?)", myConnection);
   OleDbParameter myParameter = new OleDbParameter("@Image", OleDbType.LongVarBinary, imagedata.Length);
   myParameter.Value = imagedata;
   myCommand.Parameters.Add(myParameter);

   //open the connection and execture the statement
   myConnection.Open();
   myCommand.ExecuteNonQuery();
}
finally
{
   myConnection.Close();
}

链接:

http://social.msdn.microsoft.com/Forums/en-US/ef838689-5484-4f23-bc3b-ce11c578c524/c-oledb-accessmdb-storing-and-retrieving-images?forum=adodotnetdataproviders