Search code examples
c#sqldatabaseimagememorystream

C# Saving Image to database (Not working)


Im trying to save a cover of the song to a database with row type image. Currently its not saving anything I fill into this query into the database but my other querys are working fine.

 public void AddSong(string names, string artists, string bands, string album, string strFilePath, string strlyrics, string strmp3)
    {


        if (strFilePath != null)
        {
            Image temp = new Bitmap(strFilePath);
            MemoryStream strm = new MemoryStream();
            temp.Save(strm, System.Drawing.Imaging.ImageFormat.Jpeg);
            ImageByteArray = strm.ToArray();
        }

        SqlConnection con = new SqlConnection(ConnectionString);

        //SqlConnection con = new SqlConnection(@"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\Ruben\Documents\dbPlatenCompany.mdf;Integrated Security = True; Connect Timeout = 30");
        string query = "INSERT INTO [tblSongs] ([Name], [Artist], [Band], [Album], [Cover], [lyrics], [mp3]) VALUES ('" + names + "','" + artists + "','" + bands + "','" + album + "', @IMG,'" + strlyrics + "','" + strmp3 + "')";
        SqlCommand cmd = new SqlCommand(query, con);

        try
        {
            con.Open();
            cmd.Parameters.Add(new SqlParameter("@IMG", ImageByteArray));
            cmd.BeginExecuteNonQuery();
            MessageBox.Show("gelukt");

        }

        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

EDIT: I get that storing the image in a database probally isn't the best way to go about it. But it's a small project for school so it will only be around 4 images.


Solution

  • See below code. I am hopeful that it will help- (I have only added the code to save the image in DB)

            FileStream fs = new FileStream(selectedFile, FileMode.Open, FileAccess.Read);
            byte[] bimage = new byte[fs.Length];
            fs.Read(bimage, 0, Convert.ToInt32(fs.Length));
    
            SqlConnection cn;
            cn = new SqlConnection("Data Source=.;Initial Catalog=TestDB;Integrated 
            Security=True");
            cn.Open();
            SqlCommand cmd = new SqlCommand("insert into MyTable (Image) 
            values(@imgdata)", cn);
            cmd.Parameters.AddWithValue("@imgdata", SqlDbType.Image).Value = bimage;
            cmd.ExecuteNonQuery();
            cn.Close();