-2

I'm currently working in Microsoft Visual Studio and I am doing a project for school where I have to make an app that lets you book seats at a cinema and see the description of the movie you have selected as well as leave/read a review.

In my app I have decided that I want to include pictures (basically a poster for each of the movies); I have made my Movies table and have idf as my primary key. I have added a poster column in my table definition and I have set its type to image.

My question is, how do I assign a certain image to a movie, so as to have access to it and to be able to display it later using a query of some sort?

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
  • 1
    adding image to the datanbase is not a good idea. just add the filename or path to the file – Ashkan Mobayen Khiabani Mar 02 '16 at 07:41
  • 2
    @Ashkan Mobayen Khiabani That's a wrong generalization. There are cases where it would make sense to store the images in the database. See http://stackoverflow.com/questions/3748/storing-images-in-db-yea-or-nay – L-Four Mar 02 '16 at 07:45
  • 1
    Use `varbinary(MAX)` instead of `image`. – Dai Mar 02 '16 at 07:46

2 Answers2

1

Well, first of all the poster column should be of type VARBINARY(MAX). Then you can use the following SELECT to get the contents:

using (SqlCommand cmd = new SqlCommand("SELECT poster FROM Movies WHERE IDF = @id", connection))
{
    cmd.Parameters.AddWithValue("@idf", <The movie ID>);
    byte[] imageBytes = (byte[])cmd.ExecuteScalar();

    // imageBytes is now either null or the bytes you stored in the column
}

The same goes for INSERT or UPDATE:

byte[] imageBytes = ...;

using (SqlCommand cmd = new SqlCommand("INSERT INTO Movies (..., Poster) VALUES (..., @poster)", connection))
{
    // Other parameters
    ...

    // imageBytes contains a byte array representing the image
    cmd.Parameters.AddWithValue("@poster", imageBytes);
    cmd.ExecuteNonQuery();
}

I suggest you store the raw PNG/JPEG file bytes. First of all they are already compressed, secondly you can then easily use a MemoryStream to restore the image (search SO for how to do it).

Thorsten Dittmar
  • 55,956
  • 8
  • 91
  • 139
0
insert into Movies(poster) 
SELECT BulkColumn 
FROM Openrowset( Bulk 'image..Path..here', Single_Blob) as img.

BulkColumn is syntax.

vivek verma
  • 1,716
  • 1
  • 17
  • 26