简体   繁体   中英

How To Save Image Into Database ( Java vs SQL )

I have a table in SQL 2008 Enterprise named Student_Images where the S_Images column name's data type is image. Now how can i insert the image into database. I searched on google and visited more than 50 sites some says convert it to Base64 and some say convert it to byte etc but if a column type is image then what. Please guide me.

Please don't do this. Databases are not file systems. Create a column that holds the filename and store the image in a folder.

You should not store images on the database. As pointed out on the first comment, it will take lot of space. Storing path and filename is more recommended.

I guess that maybe you did not searched the correct way as right here in stackoverflow you have a great answer about the subject .

One more thing. Your question was all capitalized, avoid that, is hard to read and therefore you will have less answers.

Look at the JDBC API Javadocs. You have to create a Blob object, fill in the data from the file and just use it as column for a (Prepared)Statement. Works just like any other data type, just a few more lines of code to create the Blob.

Here's a link to the Tutorials how to get started.

Unlike the other answers suggest, there are scenarios where storing binary data in the DB is just the best fit for the requirements. Storing just a reference to a file system can create heavy headaches with backups and also reachability problems (just because you can connect to a DB does not mean you have access to the file system where the file lives).

Yes.

  • If image size is big then it's good to create meta data of image save its reference into database and real image save on disc. This is way faster than saving image in database.
  • Saving image in database is good when your image size is small

If you want to test it to see how this works. Take any type of image and convert it to byte array stream as below:

BufferedImage originalImage = ImageIO.read(new File(
        "resources/image/Test.png"));

ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(originalImage, "jpg", baos);
baos.flush();
byte[] imageInByte = baos.toByteArray();
  • Create blob column to save data in the table
  • Execute insert statement to insert data into the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM